Java
A Java client for the LightRate token management API, providing easy-to-use methods for consuming tokens with local token bucket support for improved performance.
Installation
Add the dependency to your pom.xml:
<dependency>
<groupId>ca.lightbournetechnologies</groupId>
<artifactId>lightrate-client</artifactId>
<version>1.0.0</version>
</dependency>Or if you’re using Gradle, add to your build.gradle:
dependencies {
implementation 'ca.lightbournetechnologies:lightrate-client:1.0.0'
}Requirements:
- Java 17 or higher
Configuration
Configure the client with your API credentials:
import ca.lightbournetechnologies.lightrate.client.LightRateClient;
import ca.lightbournetechnologies.lightrate.client.ClientOptions;
// Simple usage - pass your API key and application ID
LightRateClient client = new LightRateClient("your_api_key", "your_application_id");
// With additional options
ClientOptions options = ClientOptions.builder()
.timeout(30) // optional, defaults to 30 seconds
.retryAttempts(3) // optional, defaults to 3
.defaultLocalBucketSize(10) // optional, defaults to 5
.build();
LightRateClient client = new LightRateClient("your_api_key", "your_application_id", options);Basic Usage
import ca.lightbournetechnologies.lightrate.client.LightRateClient;
import ca.lightbournetechnologies.lightrate.client.ClientOptions;
// Create a client with your API key and application ID
LightRateClient client = new LightRateClient("your_api_key", "your_application_id");
// With additional options
ClientOptions options = ClientOptions.builder()
.timeout(60)
.defaultLocalBucketSize(20)
.build();
LightRateClient client = new LightRateClient("your_api_key", "your_application_id", options);Consuming Tokens
Basic Token Consumption (Local Bucket)
The Java client uses local token buckets for efficient rate limiting. Local buckets automatically refill from the server when needed.
import ca.lightbournetechnologies.lightrate.client.LightRateClient;
import ca.lightbournetechnologies.lightrate.client.models.ConsumeLocalBucketTokenResponse;
// Consume tokens by operation (uses local token bucket)
ConsumeLocalBucketTokenResponse response = client.consumeLocalBucketToken(
"user123", // userIdentifier
"send_email" // operation
);
// Or consume tokens by path
ConsumeLocalBucketTokenResponse response = client.consumeLocalBucketToken(
"user123", // userIdentifier
null, // operation (not used when path is specified)
"/api/v1/emails/send", // path
"POST" // httpMethod (required when path is specified)
);
if (response.isSuccess()) {
System.out.println("Token consumed from " +
(response.isUsedLocalToken() ? "local bucket" : "server"));
} else {
System.out.println("Rate limited: No tokens available");
}Using Local Token Buckets
The client supports local token buckets for improved performance. Buckets are automatically created based on the rules returned by the API, and are matched against incoming requests using the matcher field from the rule.
import ca.lightbournetechnologies.lightrate.client.LightRateClient;
import ca.lightbournetechnologies.lightrate.client.ClientOptions;
// Configure client with default bucket size
ClientOptions options = ClientOptions.builder()
.defaultLocalBucketSize(20) // All operations use this bucket size
.build();
LightRateClient client = new LightRateClient("your_api_key", "your_application_id", options);
// Consume tokens using local bucket (more efficient)
ConsumeLocalBucketTokenResponse result = client.consumeLocalBucketToken(
"user123",
"send_email"
);
if (result.isSuccess()) {
System.out.println("Success! Used " +
(result.isUsedLocalToken() ? "local" : "server") + " token");
System.out.println("Bucket status: " + result.getBucketStatus());
} else {
System.out.println("Rate limited: No tokens available");
}Bucket Matching:
- Buckets are matched using the
matcherfield from the rule, which supports regex patterns - Each user has separate buckets per rule, ensuring proper isolation
- Buckets expire after 60 seconds of inactivity
- Default rules (isDefault: true) do not create local buckets
Direct HTTP API Usage
For advanced use cases where you need to bypass the local bucket and call the HTTP API directly:
import ca.lightbournetechnologies.lightrate.client.LightRateClient;
import ca.lightbournetechnologies.lightrate.client.models.ConsumeTokensResponse;
// Direct API call (bypasses local bucket)
ConsumeTokensResponse response = client.consumeTokens(
"user123", // userIdentifier
1, // tokensRequested
"send_email" // operation
);
if (response.getTokensConsumed() > 0) {
System.out.println("Consumed " + response.getTokensConsumed() +
" tokens. Remaining: " + response.getTokensRemaining());
} else {
System.out.println("Rate limited: No tokens available");
}Complete Example
import ca.lightbournetechnologies.lightrate.client.LightRateClient;
import ca.lightbournetechnologies.lightrate.client.exceptions.*;
import ca.lightbournetechnologies.lightrate.client.models.ConsumeLocalBucketTokenResponse;
// Create a client with your API key and application ID
LightRateClient client = new LightRateClient("your_api_key", "your_application_id");
try {
// Consume tokens using local bucket
ConsumeLocalBucketTokenResponse response = client.consumeLocalBucketToken(
"user123",
"send_email"
);
if (response.isSuccess()) {
System.out.println("Token consumed from " +
(response.isUsedLocalToken() ? "local bucket" : "server"));
// Proceed with your operation
sendEmailToUser("user123");
} else {
System.out.println("Rate limit exceeded. Please try again later.");
// Handle rate limiting
}
} catch (UnauthorizedException e) {
System.out.println("Authentication failed: " + e.getMessage());
} catch (TooManyRequestsException e) {
System.out.println("Rate limited: " + e.getMessage());
} catch (APIException e) {
System.out.println("API Error (" + e.getStatusCode() + "): " + e.getMessage());
} catch (NetworkException e) {
System.out.println("Network error: " + e.getMessage());
}Error Handling
The client provides comprehensive error handling with specific exception types:
import ca.lightbournetechnologies.lightrate.client.LightRateClient;
import ca.lightbournetechnologies.lightrate.client.exceptions.*;
try {
ConsumeTokensResponse response = client.consumeTokens(
"user123",
1,
"send_email"
);
} catch (UnauthorizedException e) {
System.out.println("Authentication failed: " + e.getMessage());
} catch (NotFoundException e) {
System.out.println("Resource not found: " + e.getMessage());
} catch (APIException e) {
System.out.println("API Error (" + e.getStatusCode() + "): " + e.getMessage());
} catch (NetworkException e) {
System.out.println("Network error: " + e.getMessage());
} catch (TimeoutException e) {
System.out.println("Request timed out: " + e.getMessage());
}Available Exception Types
LightRateException- Base exception classConfigurationException- Configuration-related errorsAPIException- Base API exception classBadRequestException- 400 errorsUnauthorizedException- 401 errorsForbiddenException- 403 errorsNotFoundException- 404 errorsUnprocessableEntityException- 422 errorsTooManyRequestsException- 429 errorsInternalServerException- 500 errorsServiceUnavailableException- 503 errorsNetworkException- Network-related errorsTimeoutException- Request timeout errors
API Reference
Classes
LightRateClient
Main client class for interacting with the LightRate API.
Constructor:
LightRateClient(String apiKey, String applicationId)
LightRateClient(String apiKey, String applicationId, ClientOptions options)Methods:
consumeTokens(userIdentifier, tokensRequested, operation, path, httpMethod) -> ConsumeTokensResponseconsumeLocalBucketToken(userIdentifier, operation, path, httpMethod) -> ConsumeLocalBucketTokenResponseconsumeTokensWithRequest(request) -> ConsumeTokensResponsegetAllBucketStatuses() -> Map<String, TokenBucketStatus>resetAllBuckets() -> voidgetConfiguration() -> Configuration
ClientOptions
Configuration options for the client. Use the builder pattern to create instances.
Builder Methods:
timeout(int timeout)- Request timeout in seconds (default: 30)retryAttempts(int retryAttempts)- Number of retry attempts (default: 3)defaultLocalBucketSize(int size)- Default local bucket size (default: 5)
Example:
ClientOptions options = ClientOptions.builder()
.timeout(60)
.retryAttempts(3)
.defaultLocalBucketSize(20)
.build();Types
ConsumeTokensRequestConsumeTokensResponseConsumeLocalBucketTokenResponseRuleConfigurationClientOptionsTokenBucketStatus