{"id":50699625,"url":"https://github.com/ralscha/ratelimiter-pg","last_synced_at":"2026-06-09T08:32:49.645Z","repository":{"id":344881284,"uuid":"1176871502","full_name":"ralscha/ratelimiter-pg","owner":"ralscha","description":"PostgreSQL-backed token-bucket rate-limiting library for Go.","archived":false,"fork":false,"pushed_at":"2026-05-31T13:53:15.000Z","size":91,"stargazers_count":0,"open_issues_count":4,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-05-31T15:22:47.823Z","etag":null,"topics":["go","golang","postgresql","rate-limiter"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ralscha.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-03-09T13:15:51.000Z","updated_at":"2026-05-31T13:53:19.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/ralscha/ratelimiter-pg","commit_stats":null,"previous_names":["ralscha/ratelimiter-pg"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/ralscha/ratelimiter-pg","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ralscha%2Fratelimiter-pg","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ralscha%2Fratelimiter-pg/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ralscha%2Fratelimiter-pg/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ralscha%2Fratelimiter-pg/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ralscha","download_url":"https://codeload.github.com/ralscha/ratelimiter-pg/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ralscha%2Fratelimiter-pg/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34098932,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-09T02:00:06.510Z","response_time":63,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["go","golang","postgresql","rate-limiter"],"created_at":"2026-06-09T08:32:48.908Z","updated_at":"2026-06-09T08:32:49.640Z","avatar_url":"https://github.com/ralscha.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# ratelimiter-pg\n\n`github.com/ralscha/ratelimiter-pg` is a PostgreSQL-backed token-bucket rate-limiting library for Go.\n\nIt stores bucket state in PostgreSQL and evaluates each request with one stored function call.\n\n## Install\n\n```bash\ngo get github.com/ralscha/ratelimiter-pg\n```\n\n## Quick start\n\nCall `Init` once during application startup. It is the library's single bootstrap method and prepares the schema for use.\n\n```go\npackage main\n\nimport (\n\t\"context\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com/jackc/pgx/v5/pgxpool\"\n\tratelimit \"github.com/ralscha/ratelimiter-pg\"\n)\n\nfunc main() {\n\tctx := context.Background()\n\tdb, err := pgxpool.New(ctx, \"postgres://user:pass@localhost:5432/app?sslmode=disable\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\n\tlimiter := ratelimit.New(db, \"public\", ratelimit.BucketConfig{\n\t\tCapacity:        5,\n\t\tRefillPerSecond: 1.0 / 60.0,\n\t\tCostPerRequest:  1,\n\t\tDenyRetryFloor:  time.Second,\n\t})\n\n\tif err := limiter.Init(ctx); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdecision, err := limiter.Allow(ctx, \"login:user:alice\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tlog.Printf(\"allowed=%t tokens_left=%.2f retry_after=%s\", decision.Allowed, decision.TokensLeft, decision.RetryAfter)\n}\n```\n\nWhen one request needs different settings than the limiter default, call `AllowWithConfig`:\n\n```go\ndecision, err := limiter.AllowWithConfig(ctx, \"login:user:alice\", ratelimit.BucketConfig{\n\tCapacity:        10,\n\tRefillPerSecond: 1,\n\tCostPerRequest:  2,\n\tDenyRetryFloor:  time.Second,\n})\n```\n\nMinimal request flow:\n\n1. Open a PostgreSQL connection pool.\n2. Construct `RateLimiter` with the pool and default bucket config. Leave `Schema` empty to use `public`, or set it to target a different schema.\n3. Call `Init` once during startup.\n4. Call `Allow` for each key you want to throttle, or `AllowWithConfig` when one call needs a different bucket config.\n\n## Public API\n\n- `New` constructs a `RateLimiter` with a PostgreSQL pool, target schema, and default bucket config.\n- `RateLimiter` holds the PostgreSQL pool, target schema, and default bucket config. An empty `Schema` value defaults to `public`.\n- `RateLimiter.DefaultConfig` is the bucket config used by `(*RateLimiter).Allow`.\n- `BucketConfig` defines capacity, refill rate, cost, and deny retry floor. `Capacity`, `RefillPerSecond`, and `CostPerRequest` must be `\u003e 0`, and `CostPerRequest` must not exceed `Capacity`.\n- `Decision` reports whether a request was allowed, how many tokens remain, and when to retry.\n- `(*RateLimiter).Init` prepares the limiter for use.\n- `(*RateLimiter).Allow` evaluates one key with the limiter's default bucket config. It trims leading and trailing whitespace from the key and rejects an empty result.\n- `(*RateLimiter).AllowWithConfig` evaluates one key with a call-specific bucket config override.\n- `(*RateLimiter).DeleteStaleBuckets` deletes untouched buckets older than a TTL.\n\n## Schema management\n\n`Init` is the only schema/bootstrap method exposed by the library.\n\n- `(*RateLimiter).Init` checks the current schema state and applies pending migrations when needed.\n- On a fresh database, `Init` creates the limiter objects and installs the embedded schema.\n- On an existing but outdated database, `Init` upgrades the limiter schema to the version required by the library.\n- If the database schema version is newer than the library supports, `Init` returns an error instead of downgrading or modifying it.\n- On a database that is already current, `Init` returns without applying changes.\n- Set `RateLimiter.Schema` when you want the limiter objects in a schema other than `public`.\n\n\n## Examples\n\nRunnable examples live under `examples/`:\n\n- `examples/basic` shows the smallest end-to-end limiter setup.\n- `examples/http-login` shows a login endpoint that returns `Retry-After` when throttled.\n- `examples/cleanup` shows how to delete stale bucket rows. Like the other examples, it still calls `Init` during startup.\n\nAll examples use these environment variables when present:\n\n- `DATABASE_URL` for the PostgreSQL connection string.\n- `DB_SCHEMA` for a non-default schema name.\n- `LISTEN_ADDR` for the HTTP example.\n- `STALE_TTL` for the cleanup example.\n\nIf unset, the examples default to the PostgreSQL settings from `docker-compose.yml`:\n\n- `DATABASE_URL=postgres://ratelimit:ratelimit@localhost:5432/ratelimit?sslmode=disable`\n- `DB_SCHEMA=public`\n- `LISTEN_ADDR=:8080`\n- `STALE_TTL=24h`\n\nRun them with:\n\n```bash\ngo run ./examples/basic\ngo run ./examples/http-login\ngo run ./examples/cleanup\n```\n\n## Key design\n\nThe limiter is generic. It accepts any non-empty string key chosen by the caller.\n\nExamples:\n\n```text\nlogin:user:alice\nendpoint:read_issues\ndb:read_table_query\ntenant:acme:write\n```\n\nThe library does not interpret key structure or normalize case. It only trims leading and trailing whitespace.\n\nThat makes it suitable for per-user login throttling, per-tenant quotas, per-endpoint limits, or any other string-addressable bucket strategy chosen by the application.\n\n## How it works\n\n`(*RateLimiter).Allow` validates `RateLimiter.DefaultConfig`, trims leading and trailing whitespace from the key, and then calls the PostgreSQL function `check_rate_limit`.\n\nUse `(*RateLimiter).AllowWithConfig` when a specific request should override that default configuration.\n\nThat function replenishes tokens lazily from elapsed time and atomically applies the allow-or-deny decision through one `INSERT ... ON CONFLICT ... DO UPDATE ... RETURNING` statement.\n\nBecause the decision is stored and computed in PostgreSQL, competing requests for the same bucket serialize on the same row instead of relying on in-process memory or distributed locks.\n\nFor denied requests it computes:\n\n```text\nretry_ms = ceil((cost_per_request - replenished) / refill_per_second * 1000)\n```\n\nThe deny retry floor is then applied so very small retry values still surface as a visible delay.\n\n## Database objects\n\n`Init` creates these objects in the configured schema:\n\n```sql\nCREATE TABLE public.rate_limit_schema_migrations (\n\tversion     BIGINT PRIMARY KEY,\n\tname        TEXT NOT NULL,\n\tapplied_at  TIMESTAMPTZ NOT NULL DEFAULT statement_timestamp()\n);\n\nCREATE TABLE public.rate_limit_buckets (\n\tbucket_key  TEXT PRIMARY KEY,\n\ttokens      DOUBLE PRECISION NOT NULL,\n\tupdated_at  TIMESTAMPTZ NOT NULL\n);\n\nCREATE INDEX idx_rlb_updated_at ON public.rate_limit_buckets (updated_at);\n\nCREATE OR REPLACE FUNCTION public.check_rate_limit(...)\n```\n\nThe `rate_limit_schema_migrations` table records which embedded migrations have been applied.\n\nThe `updated_at` index supports `DeleteStaleBuckets`, which removes rows that have not been touched for a configurable TTL.\n\n## Status codes and retries\n\nThe library is transport-agnostic. It returns a `Decision` with `Allowed`, `TokensLeft`, and `RetryAfter`, and the caller decides how that maps to HTTP responses, gRPC errors, CLI behavior, or background job scheduling.\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fralscha%2Fratelimiter-pg","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fralscha%2Fratelimiter-pg","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fralscha%2Fratelimiter-pg/lists"}