npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@spacetimedb/rate-limit

v0.1.0

Published

Fixed-window rate limiting and bounded expiration sweeps for SpacetimeDB TypeScript modules.

Readme

@spacetimedb/rate-limit

Limit how often a user or service can perform an action in your SpacetimeDB application. For example, allow each user to create 10 posts per minute.

Choose a limit for each action, check it before doing the work, and report how much capacity remains. Limits reset after a fixed time window, and expired tracking records are cleaned up automatically.

Install

Requires SpacetimeDB SDK, CLI, and server 2.12 or later.

Run this in your SpacetimeDB TypeScript module directory:

npm install @spacetimedb/rate-limit

Integrate into an application

Add Rate Limit to your module and initialize it. This example limits each user to 10 posts per minute:

import { schema, SenderError, t, table } from 'spacetimedb/server';
import * as rateLimit from '@spacetimedb/rate-limit/submodule';

const post = table(
  { name: 'post', public: true },
  {
    id: t.u64().primaryKey().autoInc(),
    author: t.identity(),
    body: t.string(),
    createdAt: t.timestamp(),
  }
);

const spacetimedb = schema({
  rateLimit,
  post,
});

export const init = spacetimedb.init(ctx => {
  rateLimit.install(ctx.as.rateLimit);
});

export default spacetimedb;

Configure the limit once, then check it in the same transaction that creates the post. Use the caller's identity or authenticated user ID as the key:

const postLimiter = rateLimit.client({
  scope: 'post.create',
  limit: 10,
  windowSeconds: 60,
});

export const createPost = spacetimedb.procedure(
  { body: t.string() },
  t.unit(),
  (ctx, args) => {
    ctx.withTx(tx => {
      const actor = ctx.sender.toHexString();
      const result = postLimiter.consume(tx.as.rateLimit, { key: actor });
      if (!result.allowed) throw new SenderError('post.rate_limited');
      const body = args.body.trim();
      if (!body) throw new SenderError('post.empty');
      tx.db.post.insert({
        id: 0n,
        author: ctx.sender,
        body,
        createdAt: ctx.timestamp,
      });
    });
    return {};
  }
);

The generated client calls the product-facing operation:

await conn.procedures.createPost({ body: 'Hello' });

A view can report the caller's remaining capacity with peek:

export const postLimitStatus = spacetimedb.view(
  { name: 'post_limit_status', public: true },
  t.array(
    t.object('PostLimitStatusRow', {
      limit: t.u32(),
      windowSeconds: t.u32(),
      used: t.u32(),
      remaining: t.u32(),
      resetAt: t.option(t.timestamp()),
    })
  ),
  ctx => [postLimiter.peek(ctx.db.rateLimit, ctx.sender.toHexString())]
);

Mounted as rateLimit, the submodule owns these tables:

  • rate_limit.rate_limit_bucket
  • rate_limit.rate_limit_admin_identity
  • rate_limit.rate_limit_config
  • rate_limit.rate_limit_sweep_tick

It also exposes the public admin view rate_limit.admin_rate_limit_buckets. The view returns at most 1,000 rows and returns an empty set to non-admins.

API

client({ scope, limit, windowSeconds }) configures the policy for one scope. Each scope can be configured once per module; a second client call with the same scope fails module loading with rate_limit.duplicate_scope. resetRegisteredScopes() clears the configured scopes, for example between tests that configure the same scope again. When a policy depends on application state, such as an upgrade tier, create one client per tier with its own scope. The returned limiter exposes scope, limit, and windowSeconds, plus:

  • consume(ctx, { key, cost? }) spends cost (default 1) from the actor's bucket in the caller's transaction and returns whether it was allowed, the remaining capacity, the reset time, and the retry delay. cost must be a positive integer no greater than limit; otherwise consume throws errors.invalidCost, since the request could never be allowed.
  • peek(db, key, now?) reads the actor's bucket without spending from it. Views have no clock, so a view reports an expired window until the sweep removes it; compare resetAt with the current time, or pass now from a reducer or procedure to report an expired window as fresh.

key identifies the actor; the limiter combines it with the scope. Scopes are at most 128 characters. A key must be 1 to 256 characters; otherwise consume and peek throw errors.invalidActorKey.

install(ctx) makes the publishing identity the first administrator and schedules a sweep of expired buckets every 30 seconds. Call it from the host's init reducer. Repeated installation does not add administrators or timers.

Admin operations:

  • isAdmin(db, identity) and requireAdmin(ctx) check the submodule's admin table for host operations that share its administrators.
  • addRateLimitAdmin and removeRateLimitAdmin grant and revoke access. The last administrator cannot be removed.
  • updateConfig({ sweepBatch }) sets how many expired rows each scheduled sweep deletes: 500 by default, at most 10,000.
  • runSweep({ maxRows }) deletes expired buckets now, and resetBuckets({ maxRows }) deletes buckets regardless of expiry. Both remove 500 rows by default and accept at most 10,000 per call.

errors holds the stable codes a caller can receive as a SenderError: notAuthorized, cannotRemoveLastAdmin, invalidActorKey, invalidCost, invalidSweepBatch, and invalidMaxRows. An invalid policy passed to client fails module loading instead.

Package entrypoints:

  • @spacetimedb/rate-limit/submodule supplies the submodule namespace, install, the limiter client, and the admin operations.
  • @spacetimedb/rate-limit exports client, errors, and their types.

See the Powerhouse host module for per-action and per-tier policies, caller-visible status, and admin controls.

Testing

pnpm test
pnpm run typecheck

License

Apache-2.0. See the license.