Skip to content

Custom stores

paceapi ships MemoryStore, RedisStore, MongoStore, and MemcachedStore. To keep rate limit state or cached values elsewhere (for example a database you already operate), implement the store protocol structurally—no base class required.

Limiter stores

A LimiterStore has a single method, apply(), which charges one cost against several buckets atomically. This example keeps bucket state in SQLite:

class SQLiteStore:
    """One row per bucket, evaluated and updated inside a single transaction."""

    def __init__(self, path: Path | str) -> None:
        self._path = str(path)
        # The table is created on first use, so constructing a store does no I/O.
        self._made = False

    async def apply(
        self, buckets: Sequence[Bucket], *, cost: int, force: bool, now: float | None
    ) -> list[Decision]:
        # sqlite3 is blocking, so run the step in a worker thread.
        return await asyncio.to_thread(self._step, buckets, now, cost=cost, force=force)

    def _step(
        self, buckets: Sequence[Bucket], now: float | None, *, cost: int, force: bool
    ) -> list[Decision]:
        # One connection per call: SQLite's write lock is the only lock, shared by
        # every thread and process using the file.
        with closing(self._open()) as db:
            db.execute("BEGIN IMMEDIATE")  # take the write lock before reading
            try:
                # `now=None` means the store's own clock. Read it once the lock is held,
                # so steps are timed in the order they are applied. Processes on one host
                # share it; a store shared across hosts should read time from one source.
                moment = time.time() if now is None else now
                db.execute("DELETE FROM buckets WHERE expires <= ?", (moment,))
                states = [self._read(db, bucket.key) for bucket in buckets]
                # `evaluate` applies the all-or-nothing rule: it returns new states
                # only if every bucket admitted the cost, or the cost was forced.
                new_states, decisions = evaluate(
                    buckets, states, cost=cost, force=force, now=moment
                )
                if new_states is not None:
                    for bucket, state, decision in zip(buckets, new_states, decisions, strict=True):
                        # `reset_after` is the state's TTL; zero means nothing to keep.
                        if decision.reset_after <= 0:
                            db.execute("DELETE FROM buckets WHERE key = ?", (bucket.key,))
                            continue
                        expires = moment + decision.reset_after
                        db.execute(SAVE, (bucket.key, json.dumps(state), expires))
            except BaseException:
                db.execute("ROLLBACK")
                raise
            db.execute("COMMIT")
            return decisions

    def _open(self) -> sqlite3.Connection:
        # `isolation_level=None`: transactions are managed explicitly above.
        db = sqlite3.connect(self._path, isolation_level=None, timeout=5)
        if not self._made:
            db.execute(TABLE)
            db.execute(INDEX)
            self._made = True
        return db

    @staticmethod
    def _read(db: sqlite3.Connection, key: str) -> BucketState | None:
        row = db.execute("SELECT state FROM buckets WHERE key = ?", (key,)).fetchone()
        return None if row is None else tuple(json.loads(row[0]))
# A limiter takes it as it takes any store. Every worker that opens the same file
# counts against the same limits.
limiter = Limiter(SQLiteStore(Path(tempfile.gettempdir()) / "paceapi-limits.db"))

Full example: examples/store_sqlite.py.

Stores hold state; they never make decisions. Each Bucket carries its own algorithm, and evaluate runs the algorithms over the states you load, so every algorithm works with every store. State is a short tuple of numbers: serialize it however you like (JSON here) as long as it round-trips exactly.

Contract

  • Atomic and all-or-nothing: One apply() may span several buckets (a per-second and a per-day rate). Persist the new states only if every bucket admitted the cost or the cost was forced; evaluate returns None for the states otherwise. Reading and writing must be a single atomic step, or two concurrent requests are both counted as the first. The example takes SQLite's write lock (BEGIN IMMEDIATE) before reading.
  • TTL from reset_after: Keep each state until now + reset_after and no longer, or the store grows without bound. reset_after == 0 means there is nothing to keep: delete any stored state.
  • Empty state is still state: An algorithm may return an empty tuple, which must be passed back on the next call. It is not the same as None.
  • Clock source: now is the time to evaluate at; None means the store's own clock. A store shared across machines should read one time source, as RedisStore uses the server's TIME.
  • Cancellation-safe: Limiter cancels a call that exceeds store_timeout. A cancelled call must leave the store usable; it may or may not have been counted.
  • Negative cost: evaluate raises ValueError. Quota is never refunded.

Stores that queue callers

If your store bounds in-flight calls (for example around a connection pool), also implement QueueingStore (turn()), so Limiter waits for a slot before starting store_timeout. Without it, queueing is indistinguishable from a slow server and a burst looks like an outage.

The SQLite example is such a store and omits turn() for brevity: every call waits on SQLite's single write lock, so a burst that takes longer than store_timeout to drain is handled as a store failure (allowed by default).

Contract tests

tests/stores/conformance.py is the suite the built-in stores pass. Copy it next to your tests, subclass LimiterStoreContract, and provide a store fixture:

class TestTheSQLiteStore(LimiterStoreContract):
    """The example store passes every test the memory and Redis stores pass."""

    @pytest.fixture
    def store(self, tmp_path: Path) -> LimiterStore:
        return cast("LimiterStore", sqlite_store.SQLiteStore(tmp_path / "limits.db"))

The suite does not exercise cancellation. Test that separately: cancel a call mid-flight and verify the next one succeeds.

Cache stores

A CacheStore has four methods (read, write, remove, and replace). It stores values under keys and tokens under names. A token is a random value meaning "nothing under this name has been invalidated since"; every entry records the tokens it was written under and is stale once any of them changes. This is what makes invalidation a single write.

  • read is a consistent snapshot: Return the value and the current tokens as of one moment. A store that cannot read them together reads the tokens first, as RedisStore does on a cluster for tokens in another slot. A value written in between then looks stale (a harmless miss), and a read that overlaps an invalidation can return the value from just before it. A read that starts after an invalidation must return the new token. The store does not compare tokens itself: it returns an entry with the tokens it was written under, and the cache treats a mismatch as a miss.
  • write(seen=...) is compare-and-set: Keep the value only if every token still has the value the writer saw. This is what stops a value computed during an invalidation from being cached afterwards.
  • Missing tokens are created on demand, with a value never used before. A store may evict a token at any time: entries written under it become misses, never stale hits.
  • ttl <= 0 stores nothing and removes any existing entry.
  • renew= rotates one token in the same step as a write or a removal. It cannot be combined with seen=.

Optional store capabilities:

  • Implement SweepingStore (sweep) to support purge() (removing entries under a prefix incrementally so other operations are not blocked). Stores without prefix enumeration, like MemcachedStore, omit it: purge() then invalidates, removes nothing, and returns 0.
  • Implement LockingStore (acquire and release) to support cross-process locks.

Contract tests: tests/stores/cache_conformance.py (CacheStoreContract and SweepingStoreContract—provide a store fixture and a forget method that evicts a token) and tests/stores/lock_conformance.py (provide a locks fixture). paceapi/stores/_memory_cache.py is the minimal reference implementation.