# Token bucket

> A rate limit you can watch refill: tokens grow at the real rate, requests take them, and waiting requests are carried off as each new one forms.

Rate limits are usually a line of text, “42 of 60 left”, or a bar that jumps when you send a request, so nobody can tell how fast it comes back or why a call is waiting. Token bucket draws the limiter as what it is. What’s left sits as a row of tokens packed against the outlet of a recessed tube. The next token grows at the inlet at the real refill rate, then slides down the tube to the back of the row, so an empty bucket shows as a long slide and a full one as a short step. A request takes the front token: it slips out through the outlet and the row closes up. When requests start waiting, the tube opens a queue past the outlet with a hollow slot for each one; every new token then runs the whole length of the tube straight into the first slot and carries that request away. The figure rolls as tokens come and go. The numbers are yours (your limiter’s remaining count), and between your updates the tube refills on its own.

## Install

```bash
npx shadcn@latest add https://hairlineui.com/r/token-bucket.json
```

Needs React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

- npm: none
- Hairline UI components it needs (the CLI installs them too): `number-roll`, `text-morph`
- Docs and live preview: https://hairlineui.com/ui/token-bucket
- Registry item (source): https://hairlineui.com/r/token-bucket.json

## Usage

```tsx
import { TokenBucket } from "@/components/token-bucket";

<TokenBucket limit={60} remaining={42} refillPerSecond={1} />
```

## From your API’s rate limit headers

Read the limiter’s headers after each call; the bucket refills on its own between responses.

```tsx
"use client";
import * as React from "react";
import { TokenBucket } from "@/components/token-bucket";

export function OrdersRateLimit() {
  const [limit, setLimit] = React.useState({ limit: 60, remaining: 60 });

  async function call(input: RequestInfo, init?: RequestInit) {
    const res = await fetch(input, init);
    const max = Number(res.headers.get("x-ratelimit-limit"));
    const left = Number(res.headers.get("x-ratelimit-remaining"));
    if (Number.isFinite(max) && Number.isFinite(left)) setLimit({ limit: max, remaining: left });
    return res;
  }

  // …use call() for your requests
  return <TokenBucket title="Orders API" caption="60 requests a minute" limit={limit.limit} remaining={limit.remaining} refillPerSecond={1} />;
}
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `limit` | `number` | – | How many tokens the bucket holds. |
| `remaining` | `number` | – | Tokens left now, as your limiter reports them. |
| `refillPerSecond` | `number` | `0` | Tokens added a second; the tube refills on its own between your updates. 0 for a limit that only resets. |
| `waiting` | `number` | `0` | Requests your client is holding until a token frees up. Lower it together with remaining when one is sent. |
| `title / caption` | `string` | `"Rate limit"` | The heading and a second line, e.g. the key or route. |
| `unit` | `string` | `"requests"` | What a token stands for, after the figure: “requests left”. |
| `rateLabel` | `string` | – | Replaces the refill text, which otherwise reads “+1 a second” or “+60 a minute”. |
| `color` | `string` | `--chart-1 with a quarter of --foreground` | The tokens: any CSS colour. The default leans toward your text colour so it reads on the tube in any theme, even one whose chart colours are pale greys. |
| `locales` | `string \| string[]` | – | For the figures; the visitor’s once hydrated when left out. |

## States

- **arrive**: The first time it’s seen, the tokens slide in from the inlet to their places, 14ms apart (340ms each), and the figure rolls up.
- **refill**: The next token grows from the bottom at the inlet at the refill rate; once whole it slides to the back of the row (340ms). A full bucket stops growing.
- **take**: When remaining drops, the front tokens slip out through the outlet (240ms, 30ms apart) and the row closes up (320ms). The figure rolls down.
- **waiting**: While waiting is above zero the tube narrows (420ms) and a queue opens past a hairline gate, one hollow amber slot per request, and “3 waiting” replaces the refill rate.
- **serve**: When waiting and remaining drop together, the leaving token runs into the first slot (260ms), the slot takes its colour and lifts away, and the queue moves up.
- **low**: At a tenth of the limit or less the figure turns amber.
- **reduced motion**: Tokens and slots appear and leave in place; the next token still grows, since it shows the time to the next one.

## What it handles

A rate limit shown as a count or a bar jumps on every request and never says how fast it refills, or why a call is waiting.

- **The refill you can see**: The next token grows at the real rate and slides into place; no ticking countdown.
- **Requests take a token**: Each one slips out of the outlet and the row closes up behind it.
- **Waiting, explained**: A queue opens past the outlet and each new token carries the oldest request away.
- **Your numbers stay the truth**: Pass the remaining count after each response; it refills on its own in between.
- **Any size of limit**: Up to 48 tokens across; bigger limits share a token between several requests.
- **Quiet when idle**: One frame loop grows the next token and sleeps when the bucket is full or off screen.

## Replaces

a rate limit meter, a quota bar, a usage meter, a throttle indicator, a request queue, a retry-after countdown

## Where it fits

- **API keys and developer settings**: How much of a key’s rate limit is left and how fast it comes back.
- **Clients that throttle themselves**: Calls to a third-party API held until a token frees up, shown as a queue.
- **AI message limits**: Messages or generations left in a rolling window that refills over time.
- **Status and usage dashboards**: Live headroom on an endpoint during a burst or an incident.

## Notes

- The figure is a role="meter" with the limit, what’s left, the refill and the queue in words; the tube itself is hidden from screen readers. Nothing is announced on its own, so a busy endpoint doesn’t talk over the page.
- Tokens and slots are plain elements in their own layer, moved by transform; React never re-renders while they move. One frame loop grows the next token and stops when the bucket is full, nothing refills, or the tube is off screen.
- A request doesn’t restart the refill: when remaining drops, the part of the next token already grown is kept.
- Above 48 tokens (fewer on narrow cards), each token stands for an equal share of the limit; the figure always shows the exact count.
- Installs Number roll and Text morph. With reduced motion tokens appear and leave in place.

License: MIT (https://hairlineui.com/license#components)
