Build a rate limiter
A rate limiter with one luna for each thing it limits, allowing a number of calls in each window and saying when to try again, called by a shop before each order.
At the end of this page you have a rate limiter that allows each customer five orders a minute in a shop. A refused order says how long to wait. It uses one luna for each thing it limits, calls between lunas and a declared error.
A limiter on a server needs a shared counter and a lock around it, or two requests at once both read the old count. Here each limited thing is a Limit luna of its own. Calls to one luna take turns, so the counter needs no lock.
Start from a project set up as in the Quickstart, with the TypeScript SDK installed.
The files
- luna/
- luna.config.ts
- lunas/
- index.ts
- limit.ts
- shop.ts
import { defineConfig } from "luna";
export default defineConfig({ lunas: "./lunas/index.ts" });
export { Limit } from "./limit.ts";
export { Shop } from "./shop.ts";
The limiter
import { defineLuna, t, table } from "luna";
export const Limit = defineLuna({
name: "Limit",
key: { id: t.string() },
schema: {
window: table({ start: t.timestamp(), used: t.int() }, { singleRow: true }),
},
handlers: (h) => ({
take: h({ args: { limit: t.int(), windowMs: t.int() } }, (ctx, { limit, windowMs }) => {
const now = Date.now();
const w = ctx.db.window.get();
if (!w || now >= w.start + windowMs) {
ctx.db.window.set({ start: now, used: 1 });
return { ok: true, retryAfterMs: 0 };
}
if (w.used < limit) {
ctx.db.window.update({ used: w.used + 1 });
return { ok: true, retryAfterMs: 0 };
}
return { ok: false, retryAfterMs: w.start + windowMs - now };
}),
}),
});
keynames what is limited, such as one customer in one shop. Each key is a luna of its own, created by its first call.windowis a single-row table: when the current window started, and how many calls it has used.takestarts a new window when the last one is over, counts a call while the window has room, and otherwise says how many milliseconds remain.- No
visibilitykeepsLimitprivate. Apps holding the publishable key cannot call it, so they cannot use up someone else’s limit. Your lunas can.
take never awaits, so its read and its write run with nothing in between. Two calls for the same key at once run one after the other, and the second sees the first one’s count. Calls for different keys reach different lunas and run in parallel.
The window lives in a table, not in a variable. A Limit that sleeps between calls still knows its count when it wakes.
The shop
import { defineLuna, t, table } from "luna";
import { Limit } from "./limit.ts";
export const Shop = defineLuna({
name: "Shop",
visibility: "public",
key: { id: t.string() },
schema: {
orders: table({ id: t.id(), customer: t.string(), item: t.string(), at: t.timestamp() }),
},
handlers: (h) => ({
buy: h(
{
args: { customer: t.string(), item: t.string() },
errors: { TooMany: t.object({ retryAfterMs: t.int() }) },
},
async (ctx, { customer, item }) => {
const limit = ctx.call(Limit, { id: `${ctx.key.id}:${customer}` });
const taken = await limit.take({ limit: 5, windowMs: 60_000 });
if (!taken.ok) ctx.fail("TooMany", { retryAfterMs: taken.retryAfterMs });
return ctx.db.orders.insert({ customer, item, at: Date.now() });
},
),
}),
});
ctx.call(Limit, ...)reaches the limiter for this shop and customer. Its result is typed fromtake.errorsdeclaresTooMany, andctx.failreturns it to the caller with the wait in its data.ordersgets a row only for an order the limiter allowed.
A call that succeeded stays done. If buy fails after take answered, the order is undone, but the call still counts against the limit.
Try it
Run luna dev, then load the URL and key it writes in a second terminal.
source .env.local
Place an order for the customer ann in the shop main.
curl -X POST "$LUNA_URL/Shop/main/buy" \
-H "luna-key: $LUNA_KEY" \
-H "Content-Type: application/json" \
-d '{"customer":"ann","item":"tea"}'
The first five orders in a minute return the new order’s id. The sixth fails with TooMany, and its data holds retryAfterMs. An order for another customer is counted on its own.
Next steps
- Call another luna covers
ctx.call, timeouts and retries. - Return errors shows how a declared error reaches the caller.
- The life of a luna explains why calls to one luna take turns.