UsageFlow Knowledge Base
Everything you need to know about UsageFlow, from core concepts to integration guides. Get started in minutes, not days.
What is UsageFlow?
UsageFlow is a powerful API usage tracking and management platform that helps you monitor, control, and optimize your API usage across different frameworks and languages. It's designed to make API metering so simple that setup takes minutes, not days.
UsageFlow provides framework-native packages for popular web frameworks, eliminating the need for complex configuration. The platform automatically discovers your API endpoints, tracks usage in real-time, and provides comprehensive analytics and control mechanisms.
Key Features:
Key Features:
- ✓Framework-Native Packages: Dedicated packages for Express, Fastify, NestJS, FastAPI, Flask, and Gin that feel like they were built specifically for your framework
- ✓Zero Configuration: Automatic endpoint discovery - no need to manually register routes or define which endpoints to track
- ✓Minimal Latency: Adds just 50ms of latency per request, running alongside your application without dedicated servers
- ✓Real-Time Tracking: Monitor API usage, response times, error rates, and more in real-time
- ✓Rate Limiting: Built-in rate limiting capabilities to protect your APIs
- ✓Metering & Monetization: Track usage and integrate with billing systems like Stripe
What is an Endpoint?
An endpoint in UsageFlow represents a specific API route or URL path in your application that can receive HTTP requests. Each endpoint is identified by:
Each endpoint is identified by:
- •HTTP Method: GET, POST, PUT, DELETE, PATCH, etc.
- •URL Pattern: The path pattern that matches the endpoint (e.g.,
/api/users/:id) - •Application: The application or service that hosts the endpoint
UsageFlow automatically discovers endpoints in your application by monitoring incoming requests. Once discovered, you can:
Once discovered, you can:
- →View detailed analytics and metrics for each endpoint
- →Apply policies to control access and usage
- →Set up rate limiting
- →Configure metering for billing and monetization
- →Monitor performance, error rates, and response times
💡 Example
If your API has a route GET /api/users, UsageFlow will automatically discover it and start tracking requests to that endpoint.
What is a Strategy?
A Strategy in UsageFlow defines how to identify and extract user or customer identity from incoming API requests. It specifies:
A strategy specifies:
- •Identity Field Name: The name of the field that contains the user/customer identifier (e.g.,
userId,customerId,apiKey) - •Identity Field Location: Where to look for this field - in the request headers, query parameters, or request body
Strategies are reusable configurations that can be applied to multiple policies. This allows you to:
Strategies allow you to:
- →Consistently identify users across different endpoints
- →Track usage per user or customer
- →Apply rate limits and quotas on a per-user basis
- →Enable metering and billing for specific customers
💡 Example
A strategy might extract the userId from the X-User-Id header. This strategy can then be used in policies to track usage per user.
What is a Policy?
A Policy in UsageFlow is a set of rules and configurations that control how a specific endpoint (or group of endpoints) behaves. Policies combine:
Policies combine:
- •Endpoint Pattern: Which endpoints the policy applies to (e.g.,
/api/users/*) - •HTTP Method: The specific HTTP method(s) the policy applies to
- •Strategy: How to identify the user/customer making the request
- •Rate Limiting: Optional rate limits to control request frequency
- •Metering: Optional configuration for tracking usage and billing
Policies allow you to:
Policies allow you to:
- →Apply different rules to different endpoints
- →Control access and usage on a per-user or per-customer basis
- →Enforce rate limits to protect your API from abuse
- →Enable metering for billing and monetization
- →Integrate with billing systems like Stripe
💡 Example
A policy might apply to POST /api/transactions, use a strategy to identify customers, enforce a rate limit of 100 requests per hour, and enable Stripe metering for billing.
How We Meter
UsageFlow provides flexible metering capabilities that allow you to track API usage and integrate with billing systems. Here's how it works:
Metering Expression
The metering expression defines what to count for each API request. By default, UsageFlow uses usage_record.quantity, which counts each request as 1 unit. You can customize this to count different values based on your needs.
Metering Triggers
UsageFlow supports three types of metering triggers for Stripe integration:
- →stripe_usage: Records usage directly to Stripe Usage Records, ideal for usage-based billing
- →stripe_subscription: Tracks usage in relation to Stripe subscriptions
- →stripe_invoice: Records usage for invoice generation
Automatic Tracking
Once a policy with metering is enabled, UsageFlow automatically:
- ✓Tracks each request to the endpoint
- ✓Identifies the customer using the configured strategy
- ✓Applies the metering expression to calculate usage
- ✓Sends usage data to Stripe (if Stripe integration is enabled)
- ✓Maintains usage records for analytics and reporting
Integration with Stripe
When Stripe metering is enabled, UsageFlow:
- →Requires a Stripe Price ID to associate usage with a specific product/price
- →Uses the customer identifier from the strategy to link usage to the correct Stripe customer
- →Automatically creates usage records in Stripe based on the configured trigger type
- →Supports custom event types for more granular tracking
💡 Example
If you have a policy for POST /api/ai/generate with Stripe metering enabled, each API call will be tracked and recorded to Stripe, allowing you to bill customers based on their actual usage.
Quick Start
Choose your framework below to get started with UsageFlow integration:
Node.js Frameworks
Install the UsageFlow package for your Node.js framework:
# For Express.js
npm install @usageflow/express
# For Fastify
npm install @usageflow/fastify
# For NestJS
npm install @usageflow/nestjsExpress.js
import express from 'express';
import { ExpressUsageFlowAPI } from '@usageflow/express';
const app = express();
const port = process.env.PORT || 4001;
// Initialize UsageFlow
const usageFlow = new ExpressUsageFlowAPI();
usageFlow.init('YOUR_API_KEY');
// Create middleware
const middleware = usageFlow.createMiddleware(
[{ method: '*', url: '*' }],
[{ method: 'GET', url: '/api/health' }]
);
// Use the middleware
app.use(middleware);
// Your routes here
app.get('/api/users', (req, res) => {
res.json([{ id: 1, name: 'John Doe' }]);
});Fastify
import fastify from 'fastify';
import { FastifyUsageFlowAPI } from '@usageflow/fastify';
const app = fastify();
const usageFlow = new FastifyUsageFlowAPI();
// Initialize UsageFlow
usageFlow.init('YOUR_API_KEY');
// Register UsageFlow plugin
app.register(
usageFlow.createPlugin(
[{ method: '*', url: '*' }],
[{ method: 'GET', url: '/api/health' }]
)
);NestJS
import { Module } from '@nestjs/common';
import { UsageFlowModule } from '@usageflow/nestjs';
@Module({
imports: [
UsageFlowModule.forRoot({
apiKey: 'YOUR_API_KEY',
routes: [{ method: '*', url: '*' }],
whitelistRoutes: [{ method: 'GET', url: '/api/health' }],
}),
],
})
export class AppModule {}Python Frameworks
Install the UsageFlow package for your Python framework:
# For FastAPI
pip install usageflow-fastapi
# For Flask
pip install usageflow-flaskFastAPI
from fastapi import FastAPI
from usageflow.fastapi import FastAPIUsageFlowAPI
app = FastAPI()
usage_flow = FastAPIUsageFlowAPI()
# Initialize UsageFlow
usage_flow.init('YOUR_API_KEY')
# Create middleware
middleware = usage_flow.request_interceptor(
routes=[{'method': '*', 'url': '*'}],
whitelist_routes=[{'method': 'GET', 'url': '/api/health'}]
)
# Add middleware to app
app.add_middleware(middleware)Flask
from flask import Flask
from usageflow.flask import FlaskUsageFlowAPI
app = Flask(__name__)
usage_flow = FlaskUsageFlowAPI()
# Initialize UsageFlow
usage_flow.init('YOUR_API_KEY')
# Create and apply middleware
middleware = usage_flow.request_interceptor(
routes=[{'method': '*', 'url': '*'}],
whitelist_routes=[{'method': 'GET', 'url': '/api/health'}]
)
middleware(app)Go
Install the UsageFlow package for Go:
# Install UsageFlow Go package
go get -u github.com/usageflow/goGin Framework
package main
import (
"github.com/gin-gonic/gin"
"github.com/usageflow/go"
)
func main() {
app := gin.New()
usageAPI := usageflow.UsageFlowAPI{}
usageAPI.Init("YOUR_API_KEY")
routes := []usageflow.Route{
{Method: "*", URL: "*"},
}
whitelist := []usageflow.Route{
{Method: "GET", URL: "/api/health"},
}
// Apply middleware
app.Use(usageAPI.RequestInterceptor(routes, whitelist))
}Route Patterns
UsageFlow supports various route patterns:
// Match all routes
{ method: '*', url: '*' }
// Match specific HTTP methods
{ method: 'GET', url: '/api/*' }
{ method: 'POST', url: '/api/users/*' }
// Match exact paths
{ method: 'PUT', url: '/api/users/:id' }Whitelist Routes
Exclude specific routes from tracking using the whitelist configuration.
const whitelistRoutes = [
{ method: 'GET', url: '/api/health' },
{ method: 'GET', url: '/metrics' },
{ method: '*', url: '/internal/*' },
];Metadata Collection
UsageFlow automatically collects:
- Request method and URL
- Client IP and User Agent
- Headers (sanitized)
- Query parameters
- Request body (for POST/PUT)
- Response status code
- Timing information
Advanced Usage
Custom Metadata
Add custom metadata to your requests:
// Express.js example
app.use((req, res, next) => {
req.usageflow = {
metadata: {
customField: 'value',
userId: req.user?.id,
},
};
next();
});Error Handling
UsageFlow automatically tracks API errors, but you can customize error handling as needed.
// Express.js example
app.use((err, req, res, next) => {
// UsageFlow will automatically track this error
res.status(500).json({ error: 'Internal Server Error' });
});Rate Limiting
Configure rate limits per endpoint:
const usageFlow = new ExpressUsageFlowAPI({
rateLimits: {
'/api/users': {
limit: 1000,
window: '1h',
},
},
});Best Practices
API Key Security
Never commit API keys to version control. Always use environment variables.
Route Organization
- Group similar endpoints under common prefixes
- Use consistent naming conventions
- Document route patterns clearly
Support
Need help? Contact our support team:
- Email: [email protected]
- Documentation: docs.usageflow.com
- GitHub: github.com/usageflow
