Consumption Tokens
Consumption Tokens represent a usage-based licensing model that complements the existing License Token system in Babel Licensing. While License Tokens manage concurrent access by tracking who is using your software at any given time, Consumption Tokens track the volume of service usage over time, allowing for more flexible pricing models and detailed usage analytics.
Consumption Tokens operate alongside License Tokens, providing a comprehensive approach to license management where both concurrent access and cumulative usage can be tracked.
Core Concepts
Consumption Tokens differ fundamentally from License Tokens in how they work and what they represent:
| License Tokens | Consumption Tokens |
|---|---|
| Temporarily allocated to clients | Permanently consumed during operations |
| Track concurrent usage | Track cumulative usage |
| Released when client disconnects | Never released once consumed |
| Limited by server edition | Limited by purchased or billed amount |
| Answer “who is using the license?” | Answer “how much service was used?” |
Permanent Consumption vs. Temporary Allocation
The most important distinction is that License Tokens represent a temporary allocation of a license to a specific client, while Consumption Tokens represent a permanent consumption of service resources:
- When a client disconnects, their License Token is returned to the pool and can be used by another client.
- When a service operation consumes Consumption Tokens, they are permanently deducted from the balance and cannot be reused.
Licensing Models Supported
Consumption Tokens enable two primary payment models:
Prepaid Token Model
The prepaid model supports two subscription variants:
Token-Based Prepaid
In the token-based prepaid variant, customers purchase a specific quantity of tokens upfront:
- A fixed number of tokens are added to the customer’s balance
- Tokens are deducted from their balance as services are used
- When the token balance reaches zero, service access may be restricted or additional tokens must be purchased
- Tokens may have expiration dates to encourage regular usage
- Well-suited for predictable budgeting and customers who understand their usage patterns
Money-Based Prepaid
In the money-based prepaid variant, customers prepay a monetary amount that is converted to tokens as needed:
- Customer pays a specific amount of money upfront (e.g., $1000)
- System tracks both the monetary balance and equivalent token value based on price per token
- As tokens are consumed, the monetary balance is reduced accordingly
- When the monetary balance reaches zero, service access may be restricted or additional funds must be added
- This approach is more intuitive for customers who prefer to think in terms of budget rather than tokens
Postpaid Token Model
In the postpaid model, usage is tracked throughout a billing period:
- Customers are billed at the end of the billing period based on actual usage
- Can include minimum usage commitments or tiered pricing based on volume
- Provides more flexibility for customers with variable usage patterns
- Ideal for enterprise customers who prefer regular billing cycles
Key Entity Properties
The TokenBalance entity includes these key properties for managing consumption tokens:
- Token Properties:
InitialTokenAmount- The initial number of tokens allocatedCurrentTokenBalance- The current number of tokens remaining (prepaid) or consumed (postpaid)
- Money-Based Properties:
IsMoneyBased- Indicates whether this is a money-based balanceInitialAmount- The initial monetary value for prepaid balancesCurrentBalance- The current monetary balance remaining or consumedPricePerToken- The price per token for conversion calculationsCurrency- The currency code (e.g., “USD”, “EUR”)
- Lifecycle Properties:
IsActive- Whether the balance is currently activeCreatedAt,UpdatedAt- Tracking timestampsExpiresAt- When the balance expiresPaymentModel- Prepaid (0) or Postpaid (1) as integer enum
- Billing Properties:
BillingPeriodStart,BillingPeriodEnd- For postpaid billing cyclesPackageType- Classification like “Standard”, “Enterprise”
Implementation Note: The PaymentModel property is stored as an integer where 0 = Prepaid and 1 = Postpaid, requiring casting to/from the TokenPaymentModel enum in code.
Integration with License Tokens
Consumption Tokens and License Tokens work together in a complementary fashion:
- Connection Process: When a client connects to the licensing server, a License Token is allocated from the available pool, enabling the concurrent usage tracking.
- Operation Usage: As the client performs operations (API calls, processes data, etc.), Consumption Tokens are deducted from the customer’s balance based on the specific operation and its resource requirements.
- Disconnection: When the client disconnects, the License Token is returned to the pool, but the consumed Consumption Tokens remain permanently used.
This integration allows for sophisticated licensing scenarios that consider both the number of concurrent users and the volume of service consumption.
Web Application
The Babel Licensing web application provides comprehensive management capabilities for consumption tokens through an intuitive interface designed for both administrators and license managers.
License Balance Association
Each floating license can be associated with one or more balance records that define how consumption tokens are handled for that specific license. The balance record contains essential information including:
- Consumption type: Whether the balance is token-based or money-based
- Initial and current balances: Starting amounts and remaining/consumed amounts
- Payment model: Prepaid or postpaid billing configuration
- Activation status: Flag to enable or disable the balance
- Billing period: Start and end dates for postpaid billing cycles
- Expiration settings: When the balance expires or renews
Balance Tab Interface
The web application integrates consumption token management directly into the license details view through a dedicated Balance tab. This tab displays comprehensive information about the currently active balance associated with the selected license, including:
- Current balance status: Display of remaining tokens or monetary balance
- Balance type indicators: Clear identification of prepaid vs. postpaid models
- Expiration information: Balance validity periods and renewal dates

License Balance tab showing active consumption token balance information

License Balance tab showing active money balance information
Balance Management Actions
The interface provides several management actions through strategically placed control elements:
Editing Existing Balances
You can modify the current balance by clicking the + icon located within the Balance tab. This action opens the balance editor dialog where you can:
- Adjust the current token or monetary balance
- Update expiration dates and billing periods
- Modify consumption rates and restrictions
- Change payment model settings (prepaid/postpaid)
- Activate or deactivate the balance
Creating New Balances
To create a new balance record for a license, click the $ icon located in the license row on the main licenses page. This navigates to the dedicated balances management page where you can:
- Configure a completely new balance record
- Set initial token amounts or monetary values
- Define billing cycles and payment models
- Establish consumption rules and limits
- Associate the balance with specific license features

Balance editor interface for creating and modifying token consumption settings
Configuration Options
The Consumption Token system offers several configuration options:
Token Consumption Rates
Token consumption rates determine how many tokens are deducted for each type of operation performed by your application. This granular control allows you to create pricing models that accurately reflect the resource cost and business value of different operations.
Available Operation Types
The system supports configurable token consumption for four key operation types:
// Token consumption rates configuration
public long RequiredTokensOnRequest { get; set; } // License acquisition requests
public long RequiredTokensOnValidation { get; set; } // License validation checks
public long RequiredTokensOnRelease { get; set; } // License release operations
public long RequiredTokensOnHeartbeat { get; set; } // Heartbeat/keep-alive messagesOperation-Specific Considerations
License Requests (RequiredTokensOnRequest)
- Consumed when a client requests a new license token
- Typically the highest token cost as it represents initial service access
- Consider setting higher rates for premium features or enterprise tiers
License Validations (RequiredTokensOnValidation)
- Consumed during periodic license validation checks
- Usually set to a lower rate since validations are frequent
- Balance between security (frequent validation) and cost efficiency
License Releases (RequiredTokensOnRelease)
- Consumed when a client explicitly releases a license token
- Often set to zero or minimal cost to encourage proper cleanup
- May be used to track graceful disconnections vs. timeouts
Heartbeat Operations (RequiredTokensOnHeartbeat)
- Consumed for keep-alive messages that maintain active sessions
- Typically the lowest rate since heartbeats are very frequent
- Consider setting to zero for basic connectivity maintenance
Configuration Examples
Basic Configuration - Equal consumption across all operations:
TokenUsageSettings = new TokenUsageSettings()
{
RequiredTokensOnRequest = 1,
RequiredTokensOnValidation = 1,
RequiredTokensOnRelease = 1,
RequiredTokensOnHeartbeat = 1
}Value-Based Configuration - Higher cost for initial access:
TokenUsageSettings = new TokenUsageSettings()
{
RequiredTokensOnRequest = 10, // Higher cost for license acquisition
RequiredTokensOnValidation = 2, // Moderate cost for validation
RequiredTokensOnRelease = 0, // Free to encourage proper cleanup
RequiredTokensOnHeartbeat = 1 // Minimal cost for heartbeat
}High-Frequency Configuration - Optimized for applications with frequent operations:
TokenUsageSettings = new TokenUsageSettings()
{
RequiredTokensOnRequest = 50, // Premium cost for initial access
RequiredTokensOnValidation = 1, // Low cost for frequent validations
RequiredTokensOnRelease = 0, // Free cleanup
RequiredTokensOnHeartbeat = 0 // Free heartbeat to reduce noise
}Implementation Example
The following example shows how to configure Babel Licensing with custom token consumption rates:
using Babel.Licensing;
using Babel.Licensing.Service;
// Create a new configuration object
BabelLicensingConfiguration config = new BabelLicensingConfiguration()
{
// Set the service URL
// ServiceUrl = "http://localhost:5005/", // GRPC
ServiceUrl = "http://localhost:5000/", // HTTP
// Set the public key used to verify the license signature
SignatureProvider = RSASignature.FromKeys("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDE1VRiIdr6fiVZKve7NVgjIvGdRiRx0Mjjm+Yzf6tLbzFnxLs0fat5EoRcubxx0QQQDfydsJBE/fc7cwRWSrE2xK6X4Eb4W8O47pCMjqvTQZfDqQywEZJrLlxpp9hlKz6FDYX4SagrjmP1gdw8olo+n+IBz8ubkNxRhvycikxuDQIDAQAB"),
// Set a unique client ID in case multiple instances of the application are running on the same machine
ClientId = Guid.NewGuid().ToString(),
TokenUsageSettings = new TokenUsageSettings() {
RequiredTokensOnRequest = 1,
RequiredTokensOnValidation = 1,
RequiredTokensOnRelease = 1
}
};
config.UseHttp(http => {
// Configure the HttpClient
http.Handler = new HttpClientHandler() {
// Allow self-signed certificates
ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
};
});
// Create the client object used to communicate with the server
BabelLicensing client = new BabelLicensing(config);
// Ask the user to activate the license
Console.WriteLine("Please enter your floating license key: ");
string? userKey = Console.ReadLine();
try
{
var result = await client.RequestFloatingLicenseAsync(userKey, typeof(Program));
Console.WriteLine($"License {result.License.Id} requested.");
}
catch (Exception ex)
{
Console.WriteLine($"Could not request floating license: {ex.Message}");
return;
}
try
{
// Simulate a long task which requires the allocation of a license
for (int i = 0; i < 100; i++)
{
try
{
// Validate the license
// This will contact the server to validate the license
var result = await client.ValidateLicenseAsync(userKey, typeof(Program));
Console.WriteLine($"{i}) License {result.License.Id} valid.");
}
catch (ServiceException ex)
{
Console.WriteLine($"Service error: {ex.Message} ({ex.ErrorCode})");
return;
}
catch (Exception ex)
{
Console.WriteLine($"Could not validate license: {ex.Message}");
return;
}
// Wait 1 second
await Task.Delay(200);
}
try
{
// When the application is done with the license, it can release it
await client.ReleaseFloatingLicenseAsync(userKey);
Console.WriteLine("License released.");
}
catch (Exception ex)
{
Console.WriteLine($"Could not release license: {ex.Message}");
}
}
catch (Exception ex)
{
Console.WriteLine($"License not valid: {ex.Message}");
return;
}Best Practices for Rate Configuration
- Start Conservative: Begin with lower rates and increase based on usage patterns and business needs
- Monitor Usage: Track actual consumption patterns to identify optimization opportunities
- Consider User Experience: Avoid making basic operations prohibitively expensive
- Align with Value: Set rates proportional to the business value or computational cost of operations
- Document Changes: Clearly communicate rate changes to customers in advance
- Test Thoroughly: Validate rate configurations in staging environments before production deployment
Usage Tracking and Reporting
One of the key benefits of Consumption Tokens is the detailed usage data they provide:
What is Tracked
For each token consumption event, the system records:
- Client identifier and machine information
- Operation type and timestamp
- Number of tokens consumed
- Duration and request metrics
- Associated license information
Common Usage Scenarios
Consumption Tokens are particularly well-suited for:
- SaaS Applications: Track and bill for actual usage rather than seat licenses
- API Services: Charge based on the number and type of API calls made
- Processing Services: Bill for computational resources used for data processing
- Mixed-Use Applications: Support both casual users (pay-as-you-go) and power users (subscription + consumption)
- Tiered Service Levels: Charge different rates for standard vs. premium features
Error Handling
The consumption token system provides comprehensive error handling for various scenarios:
Token Consumption Errors
When recording consumption with RecordConsumptionAsync:
ServiceException(ServiceErrorCode.BadRequest)- Tokens consumed must be greater than zeroServiceException(ServiceErrorCode.ResourceInvalidState)- No active token balance found or billing period issuesServiceException(ServiceErrorCode.ResourceExhausted)- Insufficient tokens or monetary balance for consumptionServiceException(ServiceErrorCode.ServerError)- Database operation failures
Consumption History Errors
When retrieving consumption data:
ServiceException(ServiceErrorCode.ResourceNotFound)- Token balance or license not foundServiceException(ServiceErrorCode.BadRequest)- Invalid date range (start date greater than end date)ServiceException(ServiceErrorCode.ServerError)- Database query failures
Token Balance Management Errors
When managing token balances:
ServiceException(ServiceErrorCode.ResourceNotFound)- Token balance or license not foundServiceException(ServiceErrorCode.ResourceAlreadyExists)- Active prepaid balance already existsServiceException(ServiceErrorCode.BadRequest)- Invalid operation parameters (e.g., negative tokens)ServiceException(ServiceErrorCode.ResourceInvalidState)- Cannot perform operation due to balance state
Best Practices
When implementing Consumption Tokens in your licensing strategy:
- Start with Clear Communication: Ensure customers understand how tokens are consumed and billed
- Begin with Tracking Only: Consider starting with non-enforced tracking before implementing strict token requirements
- Set Appropriate Rates: Align token consumption rates with actual value delivered or resources consumed
- Provide Usage Visibility: Give customers tools to monitor their own token consumption
- Consider Grace Periods: Implement policies for handling depleted token balances that don’t immediately cut off service
- Optimize for Common Patterns: Structure your token packages based on typical customer usage patterns
Migration Strategies
If you’re adding Consumption Tokens to an existing License Token implementation:
- Parallel Running: Start by running both systems in parallel, with Consumption Tokens in tracking-only mode
- Customer Education: Educate customers about the new model and its benefits
- Gradual Enforcement: Slowly introduce token enforcement, starting with non-critical operations
- Flexible Conversion: Offer flexible options for customers to convert between traditional licensing and token-based models
Related Documentation
For more information, refer to:
- License Tokens - Understanding the License Token system
- Floating License - How floating licenses work with License Tokens