A Redis token bucket for outbound SMS is one hash per tenant holding a token count and a timestamp, updated by a single Lua script so concurrent workers can't double-spend. Each send takes tokens equal to its segment count, and when the bucket is empty the worker waits for the time the script tells it.
We'll build it in Node with ioredis, then wire it into a send worker that calls POST /v1/messages. For the bigger design question of how to share capacity between tenants, read multi-tenant fair-share rate limiting first. This post is the implementation.
Why a token bucket
Fixed windows allow a burst at each boundary: a tenant can send a full window's worth at 11:59:59 and again at 12:00:00. A token bucket refills continuously, so the rate stays smooth, and it allows a controlled burst up to the bucket size. That matches texting: carriers throttle by second, but your tenants send in bursts when a workflow fires.
Two numbers define a bucket:
| Setting | Meaning | Example (assumed) |
|---|---|---|
rate | Tokens added per second | 3 |
burst | Bucket size, the most you can send at once | 30 |
Charge in segments, not messages. Carriers meter segments, and a 3-segment text uses 3 tokens. For context on rates, a fresh standard campaign with no vetting is about 1 to 4 segments per second, and higher use-case tiers run roughly 10 to 75. Those are approximations, so set rate from the limit on each tenant's registered campaign rather than copying a number.
Why it has to be atomic
The naive version reads the count, computes a refill, and writes it back. Two workers read at the same moment, both see 5 tokens, and both spend them. Redis runs a Lua script as one uninterrupted step, so the read, the refill and the spend can't interleave. That is the whole reason to use a script instead of GET and SET.
The Lua script
local key = KEYS[1]
local rate = tonumber(ARGV[1])
local burst = tonumber(ARGV[2])
local cost = tonumber(ARGV[3])
local t = redis.call('TIME')
local now = t[1] * 1000 + math.floor(t[2] / 1000)
local data = redis.call('HMGET', key, 'tokens', 'ts')
local tokens = tonumber(data[1])
local ts = tonumber(data[2])
if tokens == nil then
tokens = burst
ts = now
end
local elapsed = math.max(0, now - ts)
tokens = math.min(burst, tokens + elapsed * rate / 1000)
local allowed = 0
local wait_ms = 0
if tokens >= cost then
tokens = tokens - cost
allowed = 1
else
wait_ms = math.ceil((cost - tokens) * 1000 / rate)
end
redis.call('HSET', key, 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', key, math.ceil(burst / rate * 1000) * 2)
return { allowed, wait_ms } Three details matter. It reads the time from Redis (TIME), not from the worker, so clock drift between servers can't give one worker extra tokens. A new bucket starts full, so a tenant's first send isn't delayed. And the key expires after twice the time a full refill takes, so idle tenants don't leave keys behind; a missing key is just a full bucket.
If you need a tenant limit and a global limit checked together, pass both keys into one script. On Redis Cluster, give them the same hash tag, such as {sms}, so they land in the same slot.
The Node side
import Redis from 'ioredis';
import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
const redis = new Redis(process.env.REDIS_URL);
redis.defineCommand('takeTokens', {
numberOfKeys: 1,
lua: readFileSync(new URL('./take-tokens.lua', import.meta.url), 'utf8'),
});
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
export async function acquire(tenantId, segments, { rate, burst }) {
for (;;) {
const [allowed, waitMs] = await redis.takeTokens(
`sms:bucket:${tenantId}`, rate, burst, segments
);
if (allowed === 1) return;
await sleep(waitMs);
}
} If a single message costs more than burst, the loop never succeeds, so reject that case up front. In a real worker, also put a ceiling on how long a job may wait, and re-queue it instead of holding a connection open.
Sending through the API
Take the tokens, then call the API with a documented request shape:
export async function send(tenant, to, body, messageId) {
await acquire(tenant.id, estimateSegments(body), tenant.limits);
for (let attempt = 0; attempt < 5; attempt++) {
const res = await fetch('https://api.tryready.com/v1/messages', {
method: 'POST',
headers: {
'X-API-Key': process.env.READY_API_KEY,
'Content-Type': 'application/json',
'Idempotency-Key': messageId,
},
body: JSON.stringify({ to, body, consent_attested: true }),
});
if (res.ok) return res.json();
if (res.status === 409) throw new Error('quiet hours: retry after the window opens');
if (res.status === 429 || res.status >= 500) {
await sleep(Math.min(30000, 500 * 2 ** attempt));
continue;
}
throw new Error(`send failed with ${res.status}`);
}
throw new Error('send failed after retries');
} Set consent_attested to true only when the recipient agreed to receive texts from the sender. The same messageId goes on every retry, so a retry after a timeout can't send twice. A 409 QUIET_HOURS_BLOCK is a time rule, not an outage, so don't retry it in a loop; reschedule it. See handling the quiet hours 409 and the error docs.
A 429 is a signal, not a failure
Your bucket should keep you under the provider's limit, so a 429 from the API means your rate is set too high or another process is sending on the same account. Back off, and also lower the bucket's rate for a short time. Our post on SMS API rate limits covers how to read them.
FAQ
Should the bucket count messages or segments? Segments. A 3-segment text takes 3 times the carrier capacity of a 1-segment text, and a bucket that counts messages lets long texts run past the real limit.
What happens if Redis goes down? Decide the failure mode in advance. Failing closed (stop sending) is safest for compliance and cost. Failing open risks bursts. Whichever you choose, alert on it.
Is one bucket per tenant enough? Usually you want two: one per tenant for fairness, one global for the account's own ceiling. Check both in a single script so a tenant can't spend global tokens it never got.
Next step
Start with a single bucket per tenant and your own measured rate, then add the global bucket once you have more than a few active tenants. The messages docs have the full request shape, and for queue structure around the limiter, see SMS queue design for platforms.