Skip to Content
LightRateSDKsC#

C#

A C# client for the LightRate token management API, providing easy-to-use methods for consuming tokens with local token bucket support for improved performance.

Installation

Install the package via NuGet Package Manager:

Install-Package LightRateClient

Or via .NET CLI:

dotnet add package LightRateClient

Or add to your .csproj file:

<PackageReference Include="LightRateClient" Version="1.0.0" />

Configuration

Configure the client with your API credentials:

using LightRateClient.Client; using LightRateClient.Models; // Simple usage - pass your API key and application ID var client = new LightRateClient("your_api_key", "your_application_id"); // With additional options var options = new ClientOptions { Timeout = 30, // optional, defaults to 30 seconds RetryAttempts = 3, // optional, defaults to 3 DefaultLocalBucketSize = 10 // optional, defaults to 5 }; var client = new LightRateClient("your_api_key", "your_application_id", options);

Basic Usage

using LightRateClient.Client; using LightRateClient.Models; // Create a client with your API key and application ID var client = new LightRateClient("your_api_key", "your_application_id"); // With additional options var options = new ClientOptions { Timeout = 60, DefaultLocalBucketSize = 20 }; var client = new LightRateClient("your_api_key", "your_application_id", options);

Consuming Tokens

Basic Token Consumption (Local Bucket)

The C# client uses local token buckets for efficient rate limiting. Local buckets automatically refill from the server when needed.

// Consume tokens by operation (uses local token bucket) var response = client.ConsumeLocalBucketToken( userIdentifier: "user123", operation: "send_email" ); // Or consume tokens by path var response = client.ConsumeLocalBucketToken( userIdentifier: "user123", path: "/api/v1/emails/send", httpMethod: "POST" ); if (response.Success) { Console.WriteLine($"Token consumed from {(response.UsedLocalToken ? "local bucket" : "server")}"); } else { Console.WriteLine("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.

// Configure client with default bucket size var options = new ClientOptions { DefaultLocalBucketSize = 20 // All operations use this bucket size }; var client = new LightRateClient("your_api_key", "your_application_id", options); // Consume tokens using local bucket (more efficient) var result = client.ConsumeLocalBucketToken( userIdentifier: "user123", operation: "send_email" ); if (result.Success) { Console.WriteLine($"Success! Used {(result.UsedLocalToken ? "local" : "server")} token"); Console.WriteLine($"Bucket status: {result.BucketStatus}"); } else { Console.WriteLine("Rate limited: No tokens available"); }

Bucket Matching:

  • Buckets are matched using the matcher field 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:

// Direct API call (bypasses local bucket) var response = client.ConsumeTokens( userIdentifier: "user123", tokensRequested: 1, operation: "send_email" ); if (response.TokensConsumed > 0) { Console.WriteLine($"Consumed {response.TokensConsumed} tokens. Remaining: {response.TokensRemaining}"); } else { Console.WriteLine("Rate limited: No tokens available"); }

Complete Example

using LightRateClient.Client; using LightRateClient.Errors; using LightRateClient.Models; // Create a client with your API key and application ID var client = new LightRateClient("your_api_key", "your_application_id"); try { // Consume tokens using local bucket var response = client.ConsumeLocalBucketToken( userIdentifier: "user123", operation: "send_email" ); if (response.Success) { Console.WriteLine($"Token consumed from {(response.UsedLocalToken ? "local bucket" : "server")}"); // Proceed with your operation SendEmailToUser("user123"); } else { Console.WriteLine("Rate limit exceeded. Please try again later."); // Handle rate limiting } } catch (UnauthorizedError e) { Console.WriteLine($"Authentication failed: {e.Message}"); } catch (TooManyRequestsError e) { Console.WriteLine($"Rate limited: {e.Message}"); } catch (APIError e) { Console.WriteLine($"API Error ({e.StatusCode}): {e.Message}"); } catch (NetworkError e) { Console.WriteLine($"Network error: {e.Message}"); }

Error Handling

The client provides comprehensive error handling with specific exception types:

using LightRateClient.Client; using LightRateClient.Errors; try { var response = client.ConsumeTokens( userIdentifier: "user123", tokensRequested: 1, operation: "send_email" ); } catch (UnauthorizedError e) { Console.WriteLine($"Authentication failed: {e.Message}"); } catch (NotFoundError e) { Console.WriteLine($"Resource not found: {e.Message}"); } catch (APIError e) { Console.WriteLine($"API Error ({e.StatusCode}): {e.Message}"); } catch (NetworkError e) { Console.WriteLine($"Network error: {e.Message}"); } catch (TimeoutError e) { Console.WriteLine($"Request timed out: {e.Message}"); }

Available Exception Types

  • LightRateError - Base error class
  • ConfigurationError - Configuration-related errors
  • APIError - Base API error class
  • BadRequestError - 400 errors
  • UnauthorizedError - 401 errors
  • ForbiddenError - 403 errors
  • NotFoundError - 404 errors
  • UnprocessableEntityError - 422 errors
  • TooManyRequestsError - 429 errors
  • InternalServerError - 500 errors
  • ServiceUnavailableError - 503 errors
  • NetworkError - Network-related errors
  • TimeoutError - 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) -> ConsumeTokensResponse
  • ConsumeLocalBucketToken(userIdentifier, operation, path, httpMethod) -> ConsumeLocalBucketTokenResponse
  • ConsumeTokensWithRequest(request) -> ConsumeTokensResponse
  • GetAllBucketStatuses() -> Dictionary<string, TokenBucketStatus>
  • ResetAllBuckets() -> void
  • GetConfiguration() -> Configuration

ClientOptions

Configuration options for the client.

Properties:

  • Timeout (int): Request timeout in seconds (default: 30)
  • RetryAttempts (int): Number of retry attempts (default: 3)
  • DefaultLocalBucketSize (int): Default local bucket size (default: 5)

Types

  • ConsumeTokensRequest
  • ConsumeTokensResponse
  • ConsumeLocalBucketTokenResponse
  • Rule
  • Configuration
  • ClientOptions
  • TokenBucketStatus
Last updated on