Prompt
How do I build a public API with self-serve keys and billing?
Latest observation
Here’s a practical blueprint for building a public API with self-serve API keys and usage-based billing.
1) Define the product and usage model
Before writing code, decide:
-
What is billable?
- Per request
- Per response size
- Per token / compute time
- Per seat / tenant
- Tiered monthly plans
-
What limits matter?
- Requests per minute / second
- Monthly quota
- Concurrent requests
- Feature limits by plan
-
Who are the users?
- Individual developers
- Teams
- Enterprises
- Internal partners
This determines the whole account, auth, and billing design.
2) Build the core API platform
A. Authentication
Use API keys as the simplest self-serve model.
Typical flow:
- User signs up in your dashboard
- User creates a project / workspace
- User generates an API key
- Requests include the key in a header, e.g.
Authorization: Bearer sk_live_...
Best practices:
- Store only hashed keys in your database
- Show the full key only once at creation
- Support multiple keys per account
- Allow key rotation and revocation
- Track keys by environment:
testvslive
B. Authorization model
Tie each key to:
- account / workspace / project
- plan
- permissions/scopes
- status: active, disabled, expired
C. Rate limiting
Implement rate limits at the edge or API gateway:
- per key
- per account
- per IP
- per endpoint
Return proper headers:
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 42
X-RateLimit-Reset: 1730000000
3) Add usage metering
You need a system that records billable usage reliably.
What to capture per request
- API key ID
- account ID
- timestamp
- endpoint
- request units
- response units
- status code
- latency
- billable amount
- request ID / idempotency key
Design principles
- Meter at the point of truth: ideally in the API service or a gateway
- Make it idempotent so retries don’t double-bill
- Append-only usage events are safer than updating counters directly
- Reconcile usage asynchronously if needed
Common architecture
- API server emits usage event
- Event goes to queue/stream (Kafka, SQS, Pub/Sub)
- Billing processor aggregates events
- Usage database stores daily/monthly totals
- Dashboard reads from aggregated totals
4) Set up billing
A. Use a billing provider
For self-serve billing, most teams use:
- Stripe Billing
- Paddle
- Chargebee
- Recurly
Stripe is the most common for APIs.
B. Billing models
Common options:
Flat subscription
- $29/mo includes 100k requests
- overage charged after quota
Usage-based billing
- $X per 1,000 requests
- monthly invoice based on actual usage
Hybrid
- base fee + usage overage
- common for APIs
C. Stripe setup pattern
Use:
- Customer
- Subscription
- Products and Prices
- Usage records for metered billing, or invoice items for custom usage
Typical flow:
- User signs up
- Create Stripe customer
- Attach payment method
- Start subscription or enable usage-based billing
- Record usage during the month
- Stripe invoices automatically
D. Handle failed payments
Implement:
- dunning emails
- grace period
- throttling / read-only mode
- account suspension after failed retries
5) Build the developer dashboard
A self-serve API needs a good dashboard. At minimum:
- Sign up / login
- Create organization/workspace
- Create API keys
- View usage and billing
- Add payment method
- Download invoices
- Manage team members
- Set limits and alerts
- Rotate/revoke keys
- View logs and errors
- Upgrade/downgrade plan
This is what makes the API “self-serve.”
6) Create a pricing and packaging strategy
A good API pricing page should be simple:
- Free trial or free tier
- Starter tier
- Pro tier
- Enterprise/contact sales
Include:
- included usage
- overage price
- rate limits
- support level
- SLA if applicable
Keep pricing easy to understand; developers hate surprise bills.
7) Protect against abuse and billing problems
You need controls so bad actors can’t run up huge bills.
Recommended safeguards
- Require card verification for higher limits
- Free tier with low caps
- Soft limits + hard limits
- Usage alerts at 50%, 75%, 90%, 100%
- Daily spend caps
- Per-request idempotency keys
- Suspicious activity detection
- Manual review for large spikes
Anti-abuse features
- IP reputation checks
- bot detection
- CAPTCHA during signup if needed
- email verification
- domain verification for enterprise plans
8) Observability and support
For public APIs, developers expect visibility.
Provide:
- request logs
- request IDs
- status history
- latency metrics
- error breakdowns
- webhook delivery logs if applicable
Internal monitoring:
- auth failures
- key creation spikes
- usage anomalies
- billing event lag
- payment failures
- rate-limit saturation
9) API lifecycle management
Plan for:
- versioning:
/v1,/v2 - deprecation policy
- changelog
- sandbox environment
- webhook signing if you have callbacks
- backwards compatibility guarantees
10) Suggested reference architecture
A solid minimal setup:
- Frontend/dashboard: Next.js/React
- Auth: Auth0, Clerk, or custom
- API: Node/Go/Python service
- Gateway: Kong, Envoy, API Gateway, or Cloudflare
- Billing: Stripe
- Usage pipeline: queue + worker + Postgres/ClickHouse
- Logs/analytics: OpenTelemetry + Datadog/Grafana
- Secrets: Vault / KMS / cloud secret manager
11) Minimal implementation flow
Signup
- user creates account
- verify email
- create organization
- create Stripe customer
Key creation
- user clicks “Create API key”
- generate random token
- hash and store it
- show it once
Request handling
- validate key
- authorize scope/plan
- rate limit
- process request
- emit usage event
Billing
- aggregate usage daily/hourly
- send metered usage to Stripe or invoice system
- invoice monthly
- collect payment
- suspend if unpaid
12) If you want the fastest path
If you want to launch quickly, use:
- Stripe Billing for subscriptions/usage
- Clerk/Auth0 for auth
- Postgres for account and key metadata
- Redis for rate limits
- Cloudflare / API Gateway for edge protection
- A simple dashboard for self-serve onboarding
This can get you to market much faster than building billing from scratch.
13) Common mistakes to avoid
- Storing raw API keys
- Billing on request arrival instead of completed request
- No idempotency, causing double charges
- Making pricing too complex
- No usage visibility for customers
- No hard limit or spend cap
- No sandbox/test environment
- No revocation/rotation for keys
- Poor error messages and docs
14) A good MVP scope
For first launch, build only:
- signup/login
- org/project creation
- API key creation/revocation
- one usage metric
- monthly billing with Stripe
- basic dashboard with usage chart
- email alerts for overages
- docs + quickstart
That’s enough to sell a public API.
If you want, I can also give you:
- a database schema for keys, usage, and billing,
- a Stripe implementation plan, or
- a reference architecture diagram.