Knowledge Base

UsageFlow Knowledge Base

Concepts, metering, and framework guides for instrumenting your apps with UsageFlow.

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

  • Framework-Native Packages: Dedicated packages for Express, Fastify, NestJS, FastAPI, Flask, and Gin that feel like they were built specifically for your framework
  • 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 endpoint the policy applies to (e.g., /api/users/{id})
  • 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

🚀 Zero Code Required

Just install the middleware — all configuration is done from the UsageFlow console. No additional code changes needed in your application. UsageFlow handles everything behind the scenes.

Getting Started

  1. 1.Install the middleware — Add the UsageFlow package to your app (one-time setup, see installation guides below)
  2. 2.Configure in console — Set up your strategies, policies, and Stripe integration in the UsageFlow console
  3. 3.Done! — Usage is automatically tracked and reported to Stripe

What You Configure in the Console

  • Strategy: How to identify customers making requests (JWT, API Key, or custom header)
  • Tracked Endpoints: Which API routes to meter (see Route Configuration)
  • Policy: Which Stripe meter to report usage to

What UsageFlow Does For You

  • Tracks usage on your configured endpoints
  • Identifies customers based on your strategy
  • Reports usage to Stripe automatically
  • Provides analytics and usage insights in the console

💡 That's It!

Once the middleware is installed, route and policy changes are managed in the UsageFlow Console. Allow about 10 seconds for Node.js and Python agents or 30 seconds for the Go agent to refresh configuration.

Route Configuration

⚠️ Configure explicit route patterns

Empty monitoringPaths behavior differs by runtime: Node and Go currently monitor all routes, while the current Python middleware skips all routes. Add explicit patterns so behavior remains clear and portable.

After installing the UsageFlow SDK, you need to configure which API routes should be tracked and which should be excluded. This is done through the Application Configuration in the UsageFlow console.

Tracked Endpoints (Usage & Billing)

These are the API routes that UsageFlow will actively monitor, track, and meter for billing purposes. Only requests matching these paths will be tracked.

  • Add specific routes you want to meter using the syntax your framework registers, such as /api/v1/chat/:id for Express, Fastify, or Gin.
  • Node and Go accept * only as the entire method or URL. Python currently supports prefix-like URL patterns ending in *.
  • For Python routes, configure the concrete path or a supported prefix such as /api/v1/chat/*; do not reuse Node or Gin parameter syntax.
  • Choose HTTP methods (GET, POST, PUT, DELETE, etc.) or * for all methods

Tip: Use * * (method: *, path: *) to track all endpoints — but be aware this includes internal/admin routes.

Excluded Endpoints (Not Tracked)

These are routes that should be excluded from usage tracking and billing. Exclusions take precedence over tracked endpoints, allowing you to create broad tracking rules with specific exceptions.

  • Health check endpoints (e.g., /api/health)
  • Internal admin routes (e.g., /api/admin)
  • Documentation endpoints (e.g., /api/docs)
  • Any routes that shouldn't count toward customer usage

How to Configure Routes

  1. 1.Navigate to Management in the UsageFlow console
  2. 2.Select your application
  3. 3.Open the Application Configuration section
  4. 4.Add endpoint patterns to Tracked Endpoints — these will be metered
  5. 5.Add endpoint patterns to Excluded Endpoints — these will be skipped
  6. 6.Click Confirm to save your configuration

Pattern Examples

PatternMatches
GET /api/usersExact match for GET /api/users
POST /api/chat/:idExpress, Fastify, or Gin registered route pattern
POST /api/chat/*Python prefix-style route match
* *All methods on all paths (track everything)

💡 Best Practice

Start by adding specific routes you want to bill for, such as POST /api/v1/generate. Then exclude any internal routes like health checks. This approach ensures you only meter actual customer usage.

Quick Start

Follow this sequence for any of the six supported framework integrations below.

  1. 1.Install the package listed for your framework below.
  2. 2.Set the API key in your application environment:
Bash
export USAGEFLOW_API_KEY="your-api-key"
  1. 3.Register the framework middleware shown below before your routes.
  2. 4.In the application's Console Configuration, add explicit monitoringPaths and whitelistEndpoints.
  3. 5.Start the app and run its test request:
Bash
# Express
curl -i http://localhost:3000/api/users

# Fastify
curl -i http://localhost:3000/api/users

# NestJS
curl -i http://localhost:3000/api/users

# Flask
curl -i http://localhost:5000/api/users

# FastAPI
curl -i http://localhost:8000/api/users

# Gin v2
curl -i http://localhost:8080/api/users
  1. 6.For integrations that support request tracing, open Traces, select the same application, and confirm the request appears. Review the NestJS limitation below before rollout.

Node.js Frameworks

Install the UsageFlow package for your Node.js framework:

Bash
npm install @usageflow/express
npm install @usageflow/fastify
npm install @usageflow/nestjs

Express

JavaScript
import express from "express";
import { ExpressUsageFlowAPI } from "@usageflow/express";

const apiKey = process.env.USAGEFLOW_API_KEY;
if (!apiKey) throw new Error("Missing USAGEFLOW_API_KEY");

const app = express();
app.use(express.json());

const usageFlow = new ExpressUsageFlowAPI(apiKey);
app.use(usageFlow.createMiddleware());

app.get("/api/users", (_req, res) => res.json([]));

Fastify

JavaScript
import Fastify from "fastify";
import { FastifyUsageFlowAPI } from "@usageflow/fastify";

const apiKey = process.env.USAGEFLOW_API_KEY;
if (!apiKey) throw new Error("Missing USAGEFLOW_API_KEY");

const app = Fastify();
const usageFlow = new FastifyUsageFlowAPI(apiKey);
await app.register(usageFlow.createPlugin());

app.get("/api/users", async () => []);

NestJS

TypeScript
import { Module } from "@nestjs/common";
import { UsageFlowModule } from "@usageflow/nestjs";

const apiKey = process.env.USAGEFLOW_API_KEY;
if (!apiKey) throw new Error("Missing USAGEFLOW_API_KEY");

@Module({
  imports: [UsageFlowModule.forRoot({ apiKey })],
})
export class AppModule {}

Current limitation

Current limitation: module registration alone does not start request processing reliably, so NestJS request traces are not currently supported. Use the Express or Fastify package directly where possible.

Python Frameworks

Install the UsageFlow package for your Python framework:

Bash
pip install usageflow-flask
pip install usageflow-fastapi uvicorn

FastAPI

Python
import os
from fastapi import FastAPI
from usageflow.fastapi import UsageFlowMiddleware

app = FastAPI()
app.add_middleware(
    UsageFlowMiddleware,
    api_key=os.environ["USAGEFLOW_API_KEY"],
)

@app.get("/api/users")
def users():
    return []

FastAPI production limitation

Start the app with `uvicorn app:app`, send the test request, then confirm the Trace in Console. Do not enable this middleware on routes that depend on FastAPI or Starlette response background tasks; the current middleware replaces an existing response background task.

Flask

Python
import os
from flask import Flask
from usageflow.flask import UsageFlowMiddleware

app = Flask(__name__)
UsageFlowMiddleware(app, api_key=os.environ["USAGEFLOW_API_KEY"])

@app.get("/api/users")
def users():
    return []

Go

Install the UsageFlow middleware package for Go (Gin framework):

Bash
go get github.com/usageflow/usageflow-go-middleware/v2

Gin v2

The Go middleware provides request interception, usage tracking, user identification, and automatic configuration updates with graceful degradation.

Go
package main

import (
    "log"
    "os"

    "github.com/gin-gonic/gin"
    "github.com/usageflow/usageflow-go-middleware/v2/pkg/middleware"
)

func main() {
    apiKey := os.Getenv("USAGEFLOW_API_KEY")
    if apiKey == "" {
        log.Fatal("Missing USAGEFLOW_API_KEY")
    }

    router := gin.New()
    usageFlow := middleware.New(apiKey)
    router.Use(usageFlow.RequestInterceptor())

    router.GET("/api/users", func(c *gin.Context) {
        c.JSON(200, []string{})
    })

    if err := router.Run(":8080"); err != nil {
        log.Fatal(err)
    }
}

Migrating from the legacy Gin package

github.com/usageflow/usageflow-gin is deprecated and does not support Console-managed routes. Replace it with the v2 package above, register RequestInterceptor() without local route lists, then configure routes in Console.

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

Resources & Support

Find packages, examples, and get help:

Need help? Contact our support team: