---
title: Build a rate limiter
description: 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.
related:
  - /lunas/call-another-luna
  - /lunas/return-errors
  - /concepts/the-life-of-a-luna
---

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](/quickstart), with the TypeScript SDK installed.

## The files

- luna/
  - luna.config.ts
  - lunas/
    - index.ts
    - limit.ts
    - shop.ts

```ts luna/luna.config.ts
import { defineConfig } from "luna";

export default defineConfig({ lunas: "./lunas/index.ts" });
```

```ts luna/lunas/index.ts
export { Limit } from "./limit.ts";
export { Shop } from "./shop.ts";
```

## The limiter

```ts luna/lunas/limit.ts
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 };
    }),
  }),
});
```

- **`key`** names what is limited, such as one customer in one shop. Each key is a luna of its own, created by its first call.
- **`window`** is a single-row table: when the current window started, and how many calls it has used.
- **`take`** starts 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 `visibility`** keeps `Limit` private. 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

```ts luna/lunas/shop.ts
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 from `take`.
- **`errors`** declares `TooMany`, and `ctx.fail` returns it to the caller with the wait in its data.
- **`orders`** gets 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.

```bash
source .env.local
```

Place an order for the customer `ann` in the shop `main`.

```bash
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](/lunas/call-another-luna) covers `ctx.call`, timeouts and retries.
- [Return errors](/lunas/return-errors) shows how a declared error reaches the caller.
- [The life of a luna](/concepts/the-life-of-a-luna) explains why calls to one luna take turns.
