TL;DR: To avoid dropped usage events and Stripe rate limits, decouple usage ingestion from billing: a Fastify endpoint validates each event, assigns it a stable
eventIdand pushes it to AWS SQS, and a background Node.js worker reports it to Stripe's Meter Events API with that ID as the meter eventidentifier. Duplicates are expected at every hop, so deduplication happens at Stripe and in your own store, and failures land in a dead-letter queue instead of disappearing.
Key Takeaways
- Decouple usage ingestion from billing execution using a three-layer architecture: a Fastify API, AWS SQS, and a background Node.js worker.
- Reuse one
SQSClientper process. AWS SDK v3 already keeps TCP connections alive by default, so tune the HTTP handler only when measurements show socket pressure. - Give every usage event a stable
eventIdbefore it enters SQS (ideally supplied by the producer so its HTTP retries reuse it), and pass it to Stripe as the meter eventidentifier. - Keep the ingestion endpoint lightweight by strictly avoiding synchronous database queries or Stripe API calls in the critical path.
- With current
sqs-consumerversions,handleMessagemust return the message for it to be deleted. Returning nothing leaves it on the queue to be redelivered. - Stripe's Meter Events endpoint allows 1,000 calls per second per account and one concurrent call per customer per meter. Pre-aggregate or use meter event streams (API v2) for higher volumes.
You've just launched an API-first SaaS product or an AI tool with usage-based pricing. Every time a user generates an image, sends an email, or queries your database, you increment a counter. Initially, you write a simple function to push these usage events directly to Stripe's API synchronously within the request lifecycle.
Then, your product goes viral.
Suddenly, you are generating thousands of usage events per second. Stripe's Meter Events endpoint allows 1,000 calls per second per account in live mode, and only one concurrent call per customer per meter. Requests start returning 429 Too Many Requests. Your request handlers wait on Stripe, latency climbs, and incoming customer requests time out. Worst of all, usage events that failed to report are simply lost.
You are providing your service, but you aren't getting paid for it. Every dropped event is lost revenue. Conversely, if you implement naive retries and accidentally send the same event twice, you overcharge your customers, leading to chargebacks and churn.
To solve this, you must completely decouple usage ingestion from billing execution. In this guide, we will build an event-driven metering pipeline using Node.js, AWS Simple Queue Service (SQS), and Stripe. The ingestion path never waits on Stripe, every hop is safe to retry, and events that keep failing are parked in a dead-letter queue for inspection instead of being dropped.
Decoupling the Critical Path: The Architecture
The core philosophy of a resilient billing pipeline is that the ingestion layer must do as little work as possible. Its only job is to accept the payload, validate its basic schema, and push it to a highly available message queue.
Our architecture consists of three distinct layers:
- The Ingestion API: A lightweight Node.js endpoint that pushes raw usage events to AWS SQS.
- The Message Broker: AWS SQS, which acts as a shock absorber. It queues events during traffic spikes and holds them securely if downstream systems fail.
- The Metering Worker: A background Node.js process that polls SQS, skips events already reported, and sends the rest to Stripe through the Meter Events API.
To kick this off, we initialize one shared AWS SQS client with @aws-sdk/client-sqs.
// src/lib/sqs.ts
import { SQSClient } from '@aws-sdk/client-sqs';
// One client per process. SDK v3 reuses TCP connections (keep-alive) by default.
// Credentials come from the default provider chain: the ECS task role, EC2
// instance profile or Lambda execution role in AWS, or your local profile in dev.
// Never pass long-lived access keys from environment variables in production.
export const sqsClient = new SQSClient({
region: process.env.AWS_REGION ?? 'us-east-1',
});
const queueUrl = process.env.METERING_QUEUE_URL;
if (!queueUrl) throw new Error('METERING_QUEUE_URL is not set');
export const METERING_QUEUE_URL = queueUrl;
Production Note: AWS SDK for JavaScript v3 reuses connections by default, so you do not need a custom keep-alive agent. If you run very high concurrency from one process, you can pass a
NodeHttpHandlerfrom@smithy/node-http-handlerwith a largermaxSockets, but measure first. The more important rule is to create the client once at module scope rather than per request.
Building the High-Throughput Ingestion API
Your ingestion endpoint should do as little as possible. It should not call Stripe or perform heavy computation, and ideally it does not touch your primary database either.
When a user consumes resources, the system constructs a Metering Event. This event needs a unique identifier (eventId) assigned before it enters the queue, so that every later retry carries the same ID. Best of all, the producer (the service that observed the usage) supplies the ID, so that if its HTTP call to the ingestion API times out and is retried, the retry carries the same ID too. The endpoint only generates one when the producer did not.
Here is the ingestion route using Fastify, with a JSON schema so malformed input is rejected before it reaches the queue:
// src/api/ingest.ts
import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { SendMessageCommand } from '@aws-sdk/client-sqs';
import { sqsClient, METERING_QUEUE_URL } from '../lib/sqs';
import { randomUUID } from 'crypto';
interface UsagePayload {
eventId?: string; // Producer-supplied, reused on retries
customerId: string;
meterName: string; // e.g., 'api_requests', 'tokens_generated'
value: number;
}
const usageSchema = {
body: {
type: 'object',
required: ['customerId', 'meterName', 'value'],
additionalProperties: false,
properties: {
eventId: { type: 'string', format: 'uuid' },
customerId: { type: 'string', minLength: 1, maxLength: 64 },
meterName: { type: 'string', pattern: '^[a-z0-9_]{1,100}$' },
value: { type: 'number', minimum: 0 },
},
},
};
export default async function meteringRoutes(fastify: FastifyInstance) {
fastify.post(
'/v1/usage',
{ schema: usageSchema },
async (request: FastifyRequest<{ Body: UsagePayload }>, reply: FastifyReply) => {
// In production, derive customerId from the authenticated caller rather than trusting the body.
const { customerId, meterName, value } = request.body;
// 1. Reuse the producer's ID, or assign one before the event enters the queue
const eventId = request.body.eventId ?? randomUUID();
const timestamp = new Date().toISOString();
const messageBody = JSON.stringify({
eventId,
customerId,
meterName,
value,
timestamp,
});
try {
// 2. Push to SQS asynchronously
const command = new SendMessageCommand({
QueueUrl: METERING_QUEUE_URL,
MessageBody: messageBody,
// Standard queues support a nearly unlimited request rate; FIFO queues have per-queue throughput quotas.
});
await sqsClient.send(command);
// 3. Immediately return 202 Accepted
return reply.status(202).send({
status: 'accepted',
eventId,
});
} catch (error) {
request.log.error({ err: error }, 'Failed to enqueue metering event');
// 503 tells the producer to retry later with the same eventId
return reply.status(503).send({ error: 'Usage ingestion temporarily unavailable' });
}
},
);
}
By returning a 202 Accepted status, we inform the client that the event has been received but not yet processed. Because the handler does one SQS call and no database work, its throughput is bounded mainly by SQS latency and your container's CPU, so load test it with realistic payloads before sizing the service.
Implementing the SQS Worker with Idempotency
Standard SQS provides at-least-once delivery. Occasionally, AWS will deliver the same message to your worker twice. If you blindly forward these to Stripe without deduplication, your customer can be billed twice.
You cannot get true exactly-once delivery across SQS, your worker and Stripe, but you can get effectively-once billing with the Idempotent Receiver pattern. Two layers handle it here:
- Stripe deduplicates by
identifier. Every meter event carries theeventIdas itsidentifier, and Stripe enforces uniqueness for a rolling period of at least 24 hours. - Redis records completed events. After Stripe accepts an event, the worker writes a
donemarker with a 7-day TTL. Later redeliveries (for example, a message redriven from the DLQ days afterwards) are skipped before they reach Stripe.
The marker is written after the Stripe call succeeds, not before. If you claim the key first and the worker crashes before reporting, the redelivered message would be skipped as a "duplicate" and the usage would be lost.
// src/worker/consumer.ts
import { Consumer } from 'sqs-consumer';
import { sqsClient, METERING_QUEUE_URL } from '../lib/sqs';
import { createClient } from 'redis';
import { reportToStripe } from './stripeSync';
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
const app = Consumer.create({
queueUrl: METERING_QUEUE_URL,
sqs: sqsClient,
batchSize: 10, // Receive up to 10 messages per poll
handleMessage: async (message) => {
// A message we can never parse goes to the DLQ after maxReceiveCount attempts
if (!message.Body) throw new Error(`Empty message ${message.MessageId}`);
const payload = JSON.parse(message.Body);
const { eventId, customerId, meterName, value, timestamp } = payload;
const doneKey = `metering:done:${eventId}`;
// 1. Skip events we have already reported
if (await redis.exists(doneKey)) {
return message; // Returning the message acknowledges (deletes) it
}
// 2. Report to Stripe. Stripe deduplicates on `identifier` if two workers
// race on the same redelivered message.
await reportToStripe({ eventId, customerId, meterName, value, timestamp });
// 3. Record completion only after Stripe accepted the event
await redis.set(doneKey, '1', { EX: 7 * 24 * 60 * 60 });
return message;
},
});
app.on('error', (err) => console.error('SQS Consumer Error:', err.message));
app.on('processing_error', (err) => console.error('Processing Error:', err.message));
app.start();
Warning: In current
sqs-consumerreleases, a message is only deleted whenhandleMessagereturns it (unless you setalwaysAcknowledge: true). A handler that resolves withundefinedleaves every message on the queue, so each one is redelivered after the visibility timeout and eventually lands in the DLQ. IfreportToStripethrows, the message stays on the queue and SQS redelivers it, which is exactly the retry behaviour you want.
Stripe also limits Meter Events to one concurrent call per customer per meter. With batchSize: 10, a burst of events for one customer can trip that limit, so either pre-aggregate per customer before reporting (summing values over a short window) or let the SDK's retries and SQS redelivery absorb occasional 429 responses.
Integrating Stripe's Metered Billing API
Stripe's current usage-based billing is built on Meters and the Meter Events API, which replaced the legacy usage records API. Instead of updating a subscription item's quantity directly, you send usage events to a meter. Stripe aggregates them (sum, count or last value, depending on the meter's configuration) and applies the result to the invoice for the billing period.
Meter events must have a timestamp within the past 35 calendar days and no more than 5 minutes in the future, and Stripe processes them asynchronously. Report usage before the invoice for that period finalizes; an event accepted afterwards does not update a finalized invoice. If you want a team to design the metering, reconciliation and invoicing flow end to end, our API and payment gateway integration services cover Stripe billing integrations like this one.
// src/worker/stripeSync.ts
import Stripe from 'stripe';
// stripe-node pins the API version it was released with; upgrade the SDK and
// API version together, and use a version that includes Billing Meters.
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
maxNetworkRetries: 3, // Retries transient network errors with the same idempotency key
});
interface StripeSyncParams {
eventId: string;
customerId: string;
meterName: string;
value: number;
timestamp: string;
}
export async function reportToStripe(params: StripeSyncParams) {
const { eventId, customerId, meterName, value, timestamp } = params;
// Map your internal customerId to a Stripe Customer ID.
// In production, this mapping should be cached in Redis or passed in the event.
const stripeCustomerId = await resolveStripeCustomerId(customerId);
await stripe.billing.meterEvents.create(
{
event_name: meterName,
// Stripe enforces uniqueness of `identifier` for at least 24 hours
identifier: eventId,
payload: {
value: value.toString(),
stripe_customer_id: stripeCustomerId,
},
// Ensure we use the exact time the event occurred, not the processing time.
timestamp: Math.floor(new Date(timestamp).getTime() / 1000),
},
{
// Stripe's internal idempotency key provides a second layer of defense.
idempotencyKey: `stripe-meter-${eventId}`,
},
);
}
// Look up the Stripe Customer ID for your internal customer (cache this).
declare function resolveStripeCustomerId(internalId: string): Promise<string>;
The identifier and the idempotencyKey both derive from eventId. If the worker crashes after Stripe accepted the event but before it wrote the Redis marker or deleted the SQS message, the redelivered message is deduplicated by Stripe as long as it arrives within Stripe's deduplication window (at least 24 hours). Beyond that window, the Redis marker is what protects you, so keep its TTL longer than your DLQ retention and redrive delays, or store completed event IDs in your database instead.
Ensuring Reliability: Dead Letter Queues (DLQ)
What happens if Stripe's API experiences a prolonged outage? Or what if a bug produces a message that can never succeed, such as malformed JSON or a request Stripe rejects with a 400 validation error? (Some problems, such as an event_name with no matching meter, are reported asynchronously through v1.billing.meter.error_report_triggered and v1.billing.meter.no_meter_found events instead, so subscribe to those too.)
If you leave these messages in your main SQS queue, they will be endlessly retried, creating a "poison pill" that backs up your entire billing pipeline. To prevent this, you must configure a Dead Letter Queue (DLQ). A DLQ is a secondary queue where SQS automatically routes messages that have failed processing multiple times.
Here is how you provision the primary queue and its DLQ using the AWS Cloud Development Kit (CDK):
// infrastructure/BillingStack.ts
import * as sqs from 'aws-cdk-lib/aws-sqs';
import { Construct } from 'constructs';
import { Duration } from 'aws-cdk-lib';
export class BillingStack extends Construct {
constructor(scope: Construct, id: string) {
super(scope, id);
// 1. Create the Dead Letter Queue
const meteringDlq = new sqs.Queue(this, 'MeteringDLQ', {
queueName: 'metering-events-dlq',
retentionPeriod: Duration.days(14), // Keep dead letters for 2 weeks
});
// 2. Create the Primary Queue with a Redrive Policy
const meteringQueue = new sqs.Queue(this, 'MeteringQueue', {
queueName: 'metering-events-queue',
// Longer than the worst-case handler time, including Stripe SDK retries
visibilityTimeout: Duration.seconds(60),
deadLetterQueue: {
queue: meteringDlq,
maxReceiveCount: 5, // Move to DLQ after 5 failed attempts
},
});
}
}
With this configuration, any event that fails five times is safely parked in the DLQ. Your engineering team can trigger CloudWatch alerts on the DLQ depth, investigate the poison pill payloads, fix the underlying issue, and redrive the messages back to the primary queue. Remember the 35-day timestamp window: events redriven after that are rejected by Stripe, so DLQ alerts need an owner who acts within days, not weeks.
Build vs. Buy: Evaluating the Architectural Cost
At this point, you might be wondering: Should I build this event pipeline myself, or buy an off-the-shelf usage-billing solution like Metronome or Lago?
Building this architecture in Node.js and AWS SQS gives you flexibility and keeps raw usage data in your own systems. Queue costs are modest: SQS standard queues are billed per request (USD 0.40 per million in many Regions at the time of writing, after the free tier), and each event costs at least a send, a receive and a delete unless you batch. However, the engineering maintenance cost (handling edge cases, upgrading Stripe API versions, managing schema changes and reconciling usage against invoices) adds up.
If you opt to buy, you are paying for managed ingestion, rating and invoicing. A simple way to compare the options is to write the inputs down and fill them with your own numbers and vendor quotes:
# pricing-evaluation.yaml (fill with your own figures)
monthly_events: 50000000
build_in_house:
sqs_requests_per_event: 3 # send + receive + delete; batching lowers this
sqs_price_per_million_usd: 0.40 # check current pricing for your Region
redis_monthly_usd: null # your cache tier
worker_compute_monthly_usd: null # ECS/Fargate or Lambda
engineering_hours_per_month: null # on-call, upgrades, reconciliation
buy:
vendor_platform_fee_monthly_usd: null # from the vendor's quote
vendor_usage_fee_monthly_usd: null
With 50 million events and three requests per event, the queue alone is about 150 million requests, or roughly USD 60 a month before batching. The larger costs on both sides are usually people and vendor fees, not queues. The decision ultimately comes down to your engineering bandwidth and how unusual your pricing model is.
Final Thoughts on Billing Integrity
Usage-based billing demands more care than flat-rate subscriptions. By decoupling ingestion from execution using Node.js and AWS SQS, giving every event a stable identifier, deduplicating at Stripe and in your own store, and parking failures in a DLQ, you get a pipeline where retries are safe and lost usage is visible instead of silent.
Sources
- Stripe API reference: Create a billing meter event (
identifieruniqueness window, timestamp limits) - Stripe Docs: Record usage for billing with the API (Meter Events rate and concurrency limits, meter event streams, error events)
- Stripe Docs: Rate limits
- sqs-consumer README (message acknowledgement,
batchSize, events) - AWS SDK for JavaScript v3: Reuse connections with keep-alive in Node.js
Frequently Asked Questions
Why not call the Stripe API every time a usage event happens?
Calling Stripe on the request path adds latency, hits rate limits under load, and loses usage when Stripe or the network has a problem. Writing events to a queue such as SQS decouples product traffic from billing and lets a worker report usage reliably in batches.
How do you avoid billing a customer twice for the same usage?
Give every usage event a stable ID before it enters the queue, send it to Stripe as the meter event identifier, and record completed IDs in Redis or your database. Stripe deduplicates repeats for at least 24 hours and your own record covers later redeliveries, so retries and duplicate queue deliveries become harmless.
What is a dead-letter queue for in a billing pipeline?
Messages that fail repeatedly are moved to a dead-letter queue instead of blocking the main queue or being lost. You alert on it, fix the cause, and replay the messages, so no billable usage is silently dropped.
Should I build my own metering pipeline or buy a billing platform?
Build when usage is high-volume or your pricing logic is unusual enough that a platform cannot model it. Buy when your pricing is standard and billing is not a differentiator; the reconciliation, invoicing, and tax work behind a platform is larger than it looks.
