prompts.chatprompts.chatprompts.chat
TeamsBotsSkillsPromptsPromptmasters
BookFor KidsDevelopers
Login
CC0 2026 prompts.chat
DeepWikiHow to...DocsAPIPrivacyTermsSupportAboutGitHub
All Tags

Performance Prompts

40 prompts10 bots
Database Indexing taste
Taste

Opinionated rules for designing, reviewing and maintaining relational database indexes based on real query patterns.

# Database Indexing taste of a backend engineer who indexes for real queries, not guesses
- Design indexes from the actual slow query log and `EXPLAIN (ANALYZE, BUFFERS)` output, not from the schema alone. Confidence: 0.95
- Index every foreign key column that is used in joins or cascading deletes. Confidence: 0.90
- Order composite index columns by equality filters first, then range filters, then sort columns. Confidence: 0.90
- Prefer one well-chosen composite index over several single-column indexes the planner has to combine. Confidence: 0.85
- Drop indexes whose leading columns duplicate another index; `(a)` is redundant next to `(a, b)`. Confidence: 0.85
- Use covering indexes (`INCLUDE` columns) for hot read paths so queries can use index-only scans. Confidence: 0.80
- Use partial indexes for skewed data, such as `WHERE deleted_at IS NULL` or `WHERE status = 'pending'`. Confidence: 0.90
- Enforce uniqueness with unique indexes or constraints in the database, never only in application code. Confidence: 0.95
- Create indexes on large live tables with `CREATE INDEX CONCURRENTLY` (or the engine's online equivalent) in a migration of its own. Confidence: 0.95
- Never wrap indexed columns in functions in `WHERE` clauses; add an expression index like `lower(email)` when needed. Confidence: 0.85
- Avoid leading-wildcard `LIKE '%term'` on B-tree indexes; use trigram or full-text indexes for substring search. Confidence: 0.85
- Pick GIN for JSONB containment and arrays, BRIN for huge append-only time-series tables, B-tree for everything else. Confidence: 0.80
- Use keyset pagination on an indexed sort key instead of large `OFFSET` values. Confidence: 0.90
- Keep low-cardinality booleans out of standalone indexes; fold them into a partial or composite index instead. Confidence: 0.80
- Review index usage statistics monthly and remove indexes with zero scans after confirming replicas do not use them. Confidence: 0.75
- Budget write cost: every extra index slows inserts and updates, so write-heavy tables get the fewest indexes. Confidence: 0.85
- Keep table statistics fresh with autovacuum/analyze tuning on big, fast-changing tables. Confidence: 0.80
- Watch for index bloat and rebuild with `REINDEX CONCURRENTLY` when it degrades performance. Confidence: 0.70
- Name indexes predictably, for example `idx_<table>_<columns>` and `uq_<table>_<columns>`. Confidence: 0.75
- Add a query plan check to code review for any new query on a table above a million rows. Confidence: 0.70
- Test index changes on a production-sized copy or branch before shipping them. Confidence: 0.85
- Never add an index just because a column appears in a `WHERE` clause somewhere; measure first. Confidence: 0.80
Best PracticesPerformanceDatabase+2
F@f
0
Kotlin Coroutines taste
Taste

Opinionated Kotlin coroutine conventions for Android and JVM backends with structured concurrency, clear dispatchers and testable flows.

# Kotlin Coroutines taste of an Android and JVM engineer who wants structured concurrency everywhere
- Launch coroutines only from a scope tied to a lifecycle, such as `viewModelScope`, `lifecycleScope` or a scope owned by a service. Confidence: 0.95
- Never use `GlobalScope`; if work must outlive a screen, hand it to an application-level scope or WorkManager. Confidence: 0.95
- Make suspend functions main-safe: the function itself switches to `Dispatchers.IO` or `Default` with `withContext`, not the caller. Confidence: 0.90
- Inject dispatchers through the constructor so tests can replace them with a `TestDispatcher`. Confidence: 0.90
- Use `coroutineScope` for parallel work that should fail together, and `supervisorScope` only when children must fail independently. Confidence: 0.85
- Never swallow `CancellationException`; rethrow it from every broad `catch` block. Confidence: 0.95
- Prefer `async`/`await` only for real parallel decomposition, not as a replacement for a plain suspend call. Confidence: 0.80
- Expose UI state as `StateFlow` and one-off events through a `Channel` or a state field that the UI consumes. Confidence: 0.80
- Collect flows in the UI with `repeatOnLifecycle(Lifecycle.State.STARTED)` or `collectAsStateWithLifecycle`. Confidence: 0.90
- Use `stateIn` with `SharingStarted.WhileSubscribed(5_000)` so upstream work stops when nobody is watching. Confidence: 0.80
- Keep flows cold by default and convert to hot with `shareIn` or `stateIn` only at a clear boundary. Confidence: 0.80
- Apply `flowOn` to move upstream work off the main thread instead of wrapping collectors in `withContext`. Confidence: 0.80
- Wrap blocking Java APIs in `withContext(Dispatchers.IO)` and never call `runBlocking` in production code paths. Confidence: 0.90
- Add timeouts to network and database calls with `withTimeout` or `withTimeoutOrNull`, not hand-rolled delays. Confidence: 0.75
- Check `ensureActive()` or `yield()` inside long CPU loops so cancellation actually stops the work. Confidence: 0.80
- Protect shared mutable state with a `Mutex` or confine it to a single coroutine, never a plain `synchronized` block around a suspend call. Confidence: 0.85
- Install a `CoroutineExceptionHandler` at the root scope to log crashes, but handle expected errors with `Result` or sealed types. Confidence: 0.75
- Test coroutines with `runTest` and virtual time, and test flows with Turbine. Confidence: 0.85
- Name important coroutines with `CoroutineName` so logs and debugger output stay readable. Confidence: 0.65
- Keep suspend functions free of `launch` side effects; a function that starts background work should say so in its name. Confidence: 0.75
Best PracticesPerformanceAndroid+2
F@f
0
Go Concurrency taste
Taste

Opinionated Go concurrency conventions for services where every goroutine has an owner, a context and a clean way to stop.

# Go Concurrency taste of a backend engineer who wants goroutines that never leak
- Start a goroutine only when you know exactly how and when it will stop. Confidence: 0.95
- Pass a `context.Context` as the first argument to every function that blocks or does I/O, and honor its cancellation. Confidence: 0.95
- Use `errgroup.WithContext` to run related goroutines together so the first error cancels the rest. Confidence: 0.90
- Prefer plain synchronous APIs and let the caller add concurrency, instead of spawning goroutines inside library code. Confidence: 0.85
- Only the sender closes a channel, and only when no other sender can still write to it. Confidence: 0.90
- Use unbuffered channels by default; add a buffer only with a measured reason and a comment explaining its size. Confidence: 0.75
- Protect shared state with a `sync.Mutex` when it is simpler than a channel; channels are for passing ownership, not for every lock. Confidence: 0.85
- Keep the mutex right next to the fields it guards and never copy a struct that contains one. Confidence: 0.85
- Bound fan-out with a worker pool or `errgroup.SetLimit` instead of one goroutine per item. Confidence: 0.85
- Every `select` that waits on work also waits on `ctx.Done()`. Confidence: 0.90
- Use `time.NewTimer` or `context.WithTimeout` instead of `time.After` inside loops. Confidence: 0.75
- Use `sync.Once` or `sync.OnceValue` for lazy initialization, never a hand-rolled boolean flag. Confidence: 0.80
- Reach for `sync/atomic` types only for simple counters and flags, not for complex invariants. Confidence: 0.75
- Avoid `sync.Map` unless profiling shows lock contention on a read-heavy map. Confidence: 0.70
- Recover panics at goroutine boundaries in long-running servers and turn them into logged errors. Confidence: 0.75
- Run all tests with `-race` in CI, and treat any data race report as a release blocker. Confidence: 0.95
- Check for leaked goroutines in tests with `goleak`. Confidence: 0.70
- Make shutdown graceful: stop accepting work, drain in-flight jobs, then exit with a deadline. Confidence: 0.90
- Do not use `context.Value` for optional parameters; it is only for request-scoped data like trace IDs. Confidence: 0.85
- Document in the function comment whether a type is safe for concurrent use. Confidence: 0.80
Best PracticesPerformanceBackend+2
F@f
0
Python Asyncio taste
Taste

Opinionated asyncio conventions for Python services that stay fast, cancel cleanly and never block the event loop.

# Python Asyncio taste of a backend developer who never blocks the event loop
- Use asyncio only for I/O-bound work like network calls and databases; CPU-heavy work goes to a process pool. Confidence: 0.90
- Start the program with a single `asyncio.run(main())` and never create or manage event loops by hand. Confidence: 0.90
- Use `asyncio.TaskGroup` for running tasks together so a failure cancels the siblings and nothing leaks. Confidence: 0.85
- Never fire and forget with `create_task` without keeping a reference; lost tasks get garbage collected and errors vanish. Confidence: 0.90
- Put a timeout on every network call with `asyncio.timeout()`; waiting forever is a bug. Confidence: 0.90
- Limit concurrency with a `Semaphore` instead of starting thousands of requests at once. Confidence: 0.85
- Never call blocking libraries like `requests` or `time.sleep` inside a coroutine. Confidence: 0.95
- Wrap unavoidable blocking calls in `asyncio.to_thread` and keep them short. Confidence: 0.80
- Use async-native clients such as `httpx` or `asyncpg`, and share one client per app instead of one per request. Confidence: 0.85
- Treat `CancelledError` as normal: clean up in `finally` and re-raise it, never swallow it. Confidence: 0.90
- Avoid `asyncio.gather` without `return_exceptions` for independent jobs where one failure should not hide the others. Confidence: 0.70
- Use `asyncio.Queue` with a fixed number of worker tasks for producer and consumer pipelines. Confidence: 0.80
- Close clients, sessions and connections with `async with` so shutdown is clean. Confidence: 0.85
- Turn on asyncio debug mode in development to catch slow callbacks and never-awaited coroutines. Confidence: 0.75
- Keep sync and async code paths separate instead of writing clever wrappers that run both. Confidence: 0.75
- Do not mix threads and the event loop unless you use `run_coroutine_threadsafe` on purpose. Confidence: 0.80
- Test async code with `pytest-asyncio` or `anyio` and give tests their own short timeouts. Confidence: 0.80
- Use `contextvars` for request IDs and tracing data instead of globals. Confidence: 0.75
- Consider `uvloop` only after measuring; the default loop is fast enough for most services. Confidence: 0.65
- Handle SIGTERM by cancelling the main task and waiting for workers to finish in-flight jobs. Confidence: 0.80
Best PracticesPerformanceBackend+2
F@f
0
HTTP Caching taste
Taste

Opinionated HTTP caching and CDN conventions for fast web pages and APIs without stale content surprises.

# HTTP Caching taste of a web developer who wants fast pages without stale surprises
- Decide the caching policy for every response on purpose; a missing `Cache-Control` header lets browsers and proxies guess. Confidence: 0.90
- Serve fingerprinted static assets with `Cache-Control: public, max-age=31536000, immutable`. Confidence: 0.95
- Put a content hash in asset file names instead of using query strings like `?v=2` for cache busting. Confidence: 0.85
- Send HTML documents with `no-cache` or a very short max-age so new deploys show up right away. Confidence: 0.85
- Use `private, no-store` for responses with personal or sensitive data, and never let a shared cache hold them. Confidence: 0.95
- Use `s-maxage` to give the CDN a different lifetime than the browser when the CDN can be purged and the browser cannot. Confidence: 0.80
- Add `stale-while-revalidate` for content that can be a few seconds old, so users rarely wait for the origin. Confidence: 0.80
- Use `stale-if-error` so the CDN keeps serving the last good copy when the origin is down. Confidence: 0.70
- Send strong `ETag` or `Last-Modified` validators so revalidation returns a cheap `304 Not Modified`. Confidence: 0.80
- Keep the `Vary` header minimal; varying on `User-Agent` or `Cookie` quietly destroys the CDN hit rate. Confidence: 0.85
- Never cache responses that set cookies at a shared cache. Confidence: 0.90
- Purge the CDN by tag or surrogate key after content changes instead of purging everything. Confidence: 0.75
- Cache API GET responses only when the data is truly shared, and say so explicitly in the response headers. Confidence: 0.80
- Do not cache error responses for long; a cached 500 or 404 can outlive the real problem. Confidence: 0.80
- Rely on HTTP caching headers instead of a service worker unless the app truly needs offline support. Confidence: 0.70
- Watch the CDN cache hit ratio as a key metric, and investigate when it drops after a deploy. Confidence: 0.75
- Test caching behavior with `curl -I` against the real CDN, not only in local development. Confidence: 0.80
- Document the cache rules per route in one place so nobody has to read headers in the browser to learn them. Confidence: 0.65
- Keep `Cache-Control` decisions in application code or edge config under version control, not only in a dashboard. Confidence: 0.75
- Prefer short cache times plus revalidation over long cache times plus emergency purges. Confidence: 0.70
Best PracticesPerformanceCaching+2
F@f
0
Gradle Build taste
Taste

Opinionated conventions for fast, reproducible and maintainable Gradle builds on the JVM.

# Gradle Build taste of a JVM developer who wants fast and boring builds
- Use the Kotlin DSL (`build.gradle.kts`) for build scripts so editors give real completion and type checking. Confidence: 0.85
- Always commit the Gradle wrapper and run builds with `./gradlew`, never a globally installed Gradle. Confidence: 0.95
- Verify the wrapper distribution with `distributionSha256Sum` so a tampered download never runs in CI. Confidence: 0.75
- Keep every dependency and plugin version in a `gradle/libs.versions.toml` version catalog. Confidence: 0.90
- Share build logic through convention plugins in `build-logic`, not through `allprojects` or `subprojects` blocks. Confidence: 0.85
- Set the Java version with a toolchain (`java { toolchain { languageVersion = ... } }`) instead of relying on whatever JDK is installed. Confidence: 0.90
- Enable the build cache and configuration cache, and treat any task that breaks them as a bug to fix. Confidence: 0.80
- Turn on `org.gradle.parallel=true` and a sensible `org.gradle.jvmargs` in `gradle.properties` checked into the repo. Confidence: 0.80
- Register tasks lazily with `tasks.register` and the Provider API; avoid `tasks.create` and eager configuration. Confidence: 0.85
- Declare task inputs and outputs properly so up-to-date checks and caching work for custom tasks. Confidence: 0.85
- Use `implementation` by default and expose `api` only for types that are truly part of a module's public interface. Confidence: 0.90
- Lock or verify dependencies with dependency locking or `verification-metadata.xml` for builds that ship to production. Confidence: 0.70
- Never use dynamic versions like `1.+` or `latest.release` in anything that gets released. Confidence: 0.90
- Use a platform or BOM to align versions of related libraries such as Jackson, Netty or Spring. Confidence: 0.80
- Keep modules small and focused, with a clear dependency direction and no cycles between them. Confidence: 0.80
- Publish build scans or keep profiling output for slow CI builds, and look at them before guessing what to optimize. Confidence: 0.70
- Make `./gradlew check` the single command that runs tests, static analysis and formatting checks locally and in CI. Confidence: 0.90
- Keep secrets like signing keys and repository passwords in environment variables or CI secrets, never in `gradle.properties` in the repo. Confidence: 0.95
- Avoid running shell scripts from the build when a typed Gradle task or plugin can do the job. Confidence: 0.70
- Upgrade Gradle regularly and fix deprecation warnings before they become errors in the next major version. Confidence: 0.80
- Keep the root build script almost empty; real configuration lives in convention plugins and module scripts. Confidence: 0.75
Best PracticesPerformanceAutomation+1
F@f
0
MongoDB taste
Taste

Opinionated conventions for modeling, indexing and running MongoDB in production.

# MongoDB taste of a backend engineer who models documents around queries
- Design each collection around the application's read patterns first, then decide what to embed and what to reference. Confidence: 0.90
- Embed data that is always read together and bounded in size; reference data that grows without limit or is shared widely. Confidence: 0.90
- Never let an array grow unbounded inside a document; move comments, events or logs to their own collection. Confidence: 0.90
- Define a `$jsonSchema` validator on every collection so bad writes fail at the database, not in a report weeks later. Confidence: 0.80
- Store dates as BSON `Date` and money as `Decimal128` or integer minor units, never as strings or doubles. Confidence: 0.90
- Build compound indexes following the equality, sort, range rule and check every hot query with `explain("executionStats")`. Confidence: 0.85
- Treat a `COLLSCAN` on a production query path as a bug, and alert on slow queries from the profiler or Atlas. Confidence: 0.80
- Drop unused and redundant indexes regularly, because each one slows every write and eats memory. Confidence: 0.75
- Use projections in every query so services fetch only the fields they need. Confidence: 0.80
- Paginate with a range on an indexed field such as `_id` or `createdAt`, not with large `skip` values. Confidence: 0.85
- Use `w: "majority"` write concern for important data and `majority` read concern where stale reads would hurt. Confidence: 0.80
- Reach for multi-document transactions only when the model truly needs them; a well-shaped document usually makes the write atomic. Confidence: 0.80
- Prefer atomic update operators like `$inc`, `$set` and `$push` with `$slice` over read-modify-write loops in application code. Confidence: 0.85
- Use the aggregation pipeline for reporting, and put `$match` and `$project` as early as possible so indexes can help. Confidence: 0.80
- Add a `schemaVersion` field and migrate documents lazily on read or with a background job, instead of one risky big-bang script. Confidence: 0.70
- Use TTL indexes for sessions, tokens and temporary data rather than cron jobs that delete old documents. Confidence: 0.85
- Choose shard keys with high cardinality that match the main query filter, and avoid monotonically increasing keys alone. Confidence: 0.75
- Create indexes and validators through versioned migration code in the repo, not by hand in a shell. Confidence: 0.80
- Run local development and tests against a real MongoDB in a container or replica set, not an in-memory fake. Confidence: 0.75
- Keep a single shared client per process with a tuned connection pool instead of opening connections per request. Confidence: 0.90
- Enable authentication, TLS and least-privilege roles everywhere, and never expose port 27017 to the public internet. Confidence: 0.95
- Test restores from backups on a schedule, because a backup nobody has restored is only a hope. Confidence: 0.85
Best PracticesPerformanceDatabase+1
F@f
0
Nginx Config taste
Taste

Opinionated conventions for writing safe, maintainable Nginx server configurations.

# Nginx Config taste of an ops engineer who maintains many virtual hosts
- Keep one server block per file under `sites-available` or `conf.d`, named after the domain it serves. Confidence: 0.85
- Put shared settings (TLS, security headers, proxy defaults) in snippet files and `include` them instead of copying blocks. Confidence: 0.90
- Run `nginx -t` before every reload and reload with `nginx -s reload` or `systemctl reload`, never a full restart. Confidence: 0.95
- Keep configs in version control and deploy them through automation, not by editing files on the server. Confidence: 0.90
- Redirect all plain HTTP to HTTPS with a single `return 301`, and keep the port 80 block for ACME challenges only. Confidence: 0.90
- Allow only TLS 1.2 and 1.3 with a modern cipher list, and enable OCSP stapling. Confidence: 0.90
- Automate certificates with Certbot or acme.sh and alert well before expiry. Confidence: 0.90
- Add HSTS only after HTTPS works everywhere, starting with a short `max-age` before going long. Confidence: 0.80
- Set `server_tokens off` and add basic security headers (`X-Content-Type-Options`, `Referrer-Policy`, `frame-ancestors` via CSP). Confidence: 0.85
- Define a default server that returns `444` so requests with unknown Host headers never reach an app. Confidence: 0.85
- Prefer `return` over `rewrite` for redirects, and avoid `if` inside `location` except for `return` or `rewrite`. Confidence: 0.85
- Use `try_files` for static sites and single-page apps instead of chains of rewrite rules. Confidence: 0.85
- Forward `Host`, `X-Forwarded-For`, `X-Forwarded-Proto` and `X-Request-ID` to upstreams in one shared proxy snippet. Confidence: 0.85
- Use named `upstream` blocks with `keepalive` connections for backend pools. Confidence: 0.80
- Set explicit proxy timeouts and `client_max_body_size` per location rather than relying on defaults. Confidence: 0.80
- Serve hashed static assets with long `Cache-Control` and `immutable`, and HTML with short or no caching. Confidence: 0.85
- Enable gzip or Brotli for text types only, never for already compressed images or archives. Confidence: 0.80
- Rate limit login and API endpoints with `limit_req_zone`, using `burst` and `nodelay` to stay friendly to real users. Confidence: 0.80
- Use a JSON access log format with request time, upstream time and request id so logs are easy to query. Confidence: 0.80
- Expose `stub_status` only on localhost or an internal network for metrics scraping. Confidence: 0.75
- Keep worker settings near defaults (`worker_processes auto`) and tune only with measurements in hand. Confidence: 0.70
Best PracticesSecurityPerformance+1
F@f
0
SQLite taste
Taste

Opinionated conventions for running SQLite reliably in real applications.

# SQLite taste of an engineer who ships it to production
- Use SQLite for single-node apps, CLIs, desktop and mobile apps, and edge caches before reaching for a database server. Confidence: 0.85
- Turn on WAL mode (`PRAGMA journal_mode = WAL`) so readers never block the writer. Confidence: 0.95
- Set `PRAGMA foreign_keys = ON` on every connection, since it is off by default. Confidence: 0.95
- Set a `busy_timeout` of a few seconds instead of letting writes fail immediately with `SQLITE_BUSY`. Confidence: 0.90
- Use `PRAGMA synchronous = NORMAL` with WAL for a good balance of durability and speed. Confidence: 0.75
- Funnel all writes through a single connection or queue, and use a pool of read-only connections for reads. Confidence: 0.80
- Start write transactions with `BEGIN IMMEDIATE` to avoid deadlocks when a read transaction tries to upgrade. Confidence: 0.80
- Declare tables `STRICT` on new schemas so type affinity does not silently store text in integer columns. Confidence: 0.80
- Store timestamps as ISO 8601 text or Unix epoch integers consistently, and pick one convention per database. Confidence: 0.85
- Use `INTEGER PRIMARY KEY` for row ids unless you need globally unique ids, then add a separate UUID or ULID column. Confidence: 0.75
- Batch many inserts inside one transaction; thousands of autocommit inserts are slow. Confidence: 0.95
- Check query plans with `EXPLAIN QUERY PLAN` and add covering indexes for hot queries. Confidence: 0.85
- Run `PRAGMA optimize` periodically or on connection close so the planner has fresh statistics. Confidence: 0.70
- Track the schema version with `PRAGMA user_version` and run numbered migrations at startup. Confidence: 0.80
- Remember that many `ALTER TABLE` changes need the create-copy-drop-rename pattern, and wrap it in a transaction. Confidence: 0.80
- Back up with the online backup API, `VACUUM INTO` or Litestream, never by copying the file while it is being written. Confidence: 0.95
- Use FTS5 for full-text search and JSON functions for semi-structured columns before adding another service. Confidence: 0.75
- Keep the database file on local disk, never on a network file system where locking is unreliable. Confidence: 0.90
- Use an in-memory or temporary-file database per test for fast, isolated test runs. Confidence: 0.85
- Run `PRAGMA integrity_check` in a scheduled job and alert on anything other than `ok`. Confidence: 0.65
Best PracticesPerformanceDatabase+1
F@f
0
API Rate Limiting taste
Taste

Opinionated conventions for designing fair, observable and abuse-resistant API rate limits.

# API Rate Limiting taste of a backend platform engineer
- Rate limit every public endpoint from day one, including authenticated ones; abuse rarely announces itself in advance. Confidence: 0.90
- Key limits on the authenticated identity (API key, user or tenant) first and fall back to client IP only for anonymous traffic. Confidence: 0.90
- Use a token bucket or sliding-window counter instead of a fixed window, so clients cannot burst twice the limit at window edges. Confidence: 0.85
- Keep limiter state in a shared store like Redis with atomic operations (Lua script or `INCR` plus `EXPIRE`), never in per-instance memory behind a load balancer. Confidence: 0.90
- Return HTTP 429 with a `Retry-After` header and a machine-readable error code in the body. Confidence: 0.95
- Send `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset` headers on every response so clients can pace themselves. Confidence: 0.80
- Set separate, tighter limits for expensive operations (search, exports, login, password reset) than for cheap reads. Confidence: 0.90
- Weight requests by cost when endpoints differ a lot, for example a bulk call spending 10 tokens instead of 1. Confidence: 0.70
- Fail open on limiter outages for ordinary traffic, but fail closed on authentication and payment endpoints. Confidence: 0.75
- Apply a coarse global limit at the edge (CDN or gateway) and finer per-tenant limits in the application. Confidence: 0.85
- Publish the limits in the API docs and changelog, and give advance notice before lowering them. Confidence: 0.85
- Offer higher limits through plans or explicit allowlists instead of silent exceptions hardcoded in the limiter. Confidence: 0.75
- Ship official SDKs with automatic retries on 429 using exponential backoff with jitter and respect for `Retry-After`. Confidence: 0.85
- Distinguish rate limits (requests over time) from quotas (monthly usage) and concurrency limits, and report each with its own error code. Confidence: 0.75
- Log and meter every throttled request by key and route, and alert when a single tenant suddenly dominates rejections. Confidence: 0.85
- Run new limits in shadow mode first, logging what would be blocked, before enforcing them. Confidence: 0.80
- Never include the reason a login was throttled in a way that reveals whether the account exists. Confidence: 0.80
- Add per-account login throttling on top of per-IP throttling to slow credential stuffing from rotating IPs. Confidence: 0.85
- Keep limiter configuration in code or config files with review, not in an ad hoc admin toggle. Confidence: 0.70
- Load test the limiter itself; it sits on the hot path and must add only a millisecond or two of latency. Confidence: 0.75
Best PracticesSecurityPerformance+2
F@f
0
Tokio Async Rust taste
Taste

Opinionated conventions for writing reliable, observable async Rust services with Tokio.

# Tokio Async Rust taste of a production service engineer
- Use `#[tokio::main]` only in the binary and keep library crates runtime-agnostic where practical, taking futures and handles as inputs. Confidence: 0.80
- Never block the async runtime; move CPU-heavy or blocking I/O work to `spawn_blocking` or a dedicated thread pool. Confidence: 0.95
- Use `tokio::sync::Mutex` only when a lock must be held across an `.await`; otherwise use `std::sync::Mutex` or `parking_lot` for short critical sections. Confidence: 0.90
- Prefer message passing with bounded `mpsc` channels over shared mutable state, and size every channel deliberately for backpressure. Confidence: 0.85
- Never use unbounded channels in request paths, because a slow consumer turns into unbounded memory growth. Confidence: 0.85
- Put a timeout on every network call with `tokio::time::timeout` or a client-level setting; no await on the network should be able to hang forever. Confidence: 0.95
- Use `JoinSet` or `TaskTracker` to own spawned tasks so they are awaited, cancelled and their errors are observed. Confidence: 0.85
- Treat every `.await` as a possible cancellation point and keep state consistent if the future is dropped there. Confidence: 0.85
- Use `select!` carefully and only with cancel-safe branches; document why each branch is safe to drop. Confidence: 0.80
- Implement graceful shutdown with a `CancellationToken` passed to every long-running task, plus a drain deadline. Confidence: 0.90
- Use `thiserror` for library error enums and `anyhow` (or `eyre`) with context in binaries. Confidence: 0.85
- Instrument with `tracing`, using `#[instrument(skip_all, fields(...))]` on handlers and structured fields instead of formatted strings. Confidence: 0.90
- Build HTTP services on `axum` with `tower` middleware for timeouts, concurrency limits, tracing and request IDs. Confidence: 0.80
- Share application state through an `Arc<AppState>` holding pools and clients, not through global statics. Confidence: 0.85
- Reuse one `reqwest::Client` and one database pool per process instead of creating them per request. Confidence: 0.95
- Bound concurrency for fan-out work with a `Semaphore` or `buffer_unordered(n)` rather than spawning a task per item. Confidence: 0.85
- Avoid holding guards or non-`Send` values across `.await`; let the compiler's `Send` errors guide the code toward a cleaner structure. Confidence: 0.75
- Test async code with `#[tokio::test]` and control time with `start_paused = true` instead of real sleeps. Confidence: 0.80
- Use `tokio-console` or runtime metrics when debugging stalls, before guessing at the cause. Confidence: 0.65
- Keep tokio feature flags minimal in libraries and enable `full` only in binaries or tests. Confidence: 0.70
Best PracticesPerformanceBackend
F@f
0
Vite Frontend Tooling taste
Taste

Opinionated conventions for fast, type-safe frontend builds and tooling with Vite.

# Vite Frontend Tooling taste of a fast-feedback web developer
- Start new single-page apps and component playgrounds on Vite with the official framework plugin instead of a custom webpack setup. Confidence: 0.85
- Keep `vite.config.ts` in TypeScript with `defineConfig`, and keep it short enough to read in one screen. Confidence: 0.80
- Run type checking separately with `tsc --noEmit` in CI and in a watcher, since Vite only strips types and never checks them. Confidence: 0.95
- Use path aliases sparingly, define them once in `tsconfig.json`, and mirror them in Vite with a plugin such as `vite-tsconfig-paths`. Confidence: 0.75
- Expose only `VITE_`-prefixed environment variables to client code and never put secrets in them. Confidence: 0.95
- Type `import.meta.env` in a `vite-env.d.ts` file so missing or misspelled variables fail at compile time. Confidence: 0.80
- Configure the dev server proxy for backend APIs instead of enabling permissive CORS on the backend just for local development. Confidence: 0.85
- Use Vitest for unit and component tests so tests share the same config, transforms and aliases as the app. Confidence: 0.90
- Lazy-load routes and heavy widgets with dynamic `import()` and let Rollup split chunks, rather than hand-tuning `manualChunks` early. Confidence: 0.80
- Inspect bundle size with `rollup-plugin-visualizer` before releases and treat a large new dependency as a review topic. Confidence: 0.75
- Import assets through the module graph so they get hashed file names, keeping `public/` for files that need fixed URLs like `robots.txt`. Confidence: 0.85
- Set an explicit `build.target` that matches the browsers you support, instead of relying on the default. Confidence: 0.70
- Generate source maps for production builds and upload them to your error tracker rather than serving them publicly. Confidence: 0.80
- Prefer native CSS features and CSS modules or Tailwind over heavy CSS-in-JS runtimes in Vite projects. Confidence: 0.70
- Keep the plugin list small and remove plugins that duplicate built-in features such as JSON imports or CSS handling. Confidence: 0.80
- Use `vite preview` to smoke-test the production build locally before deploying, since dev and build use different pipelines. Confidence: 0.85
- Pin Vite and plugin versions in the lockfile and upgrade them together, reading the migration guide for major versions. Confidence: 0.85
- Use library mode with `vite build --lib` plus a declaration generator when publishing a component package, and mark peer dependencies as external. Confidence: 0.75
- Fix slow cold starts by checking `optimizeDeps` and large barrel files before blaming Vite itself. Confidence: 0.70
- Fail CI on build warnings about circular imports or missing exports instead of letting them pile up. Confidence: 0.65
PerformanceToolingFrontend+2
F@f
0
Cloudflare Worker taste
Taste

Opinionated conventions for focused, well-bound Cloudflare Workers at the edge.

# Cloudflare Worker taste of an edge-first platform engineer
- Prefer Wrangler for local dev, secrets, and deploys; keep `wrangler.toml` (or `wrangler.json`) as the source of truth for bindings. Confidence: 0.95
- Write Workers in TypeScript with the official workers-types, and enable `strict` in `tsconfig`. Confidence: 0.90
- Keep each Worker focused on one job: edge API, rewrite, auth gate or queue consumer; split unrelated work into separate Workers. Confidence: 0.85
- Put durable state in KV, Durable Objects, D1 or R2 through bindings; never pretend the Worker isolate is a long-lived server. Confidence: 0.90
- Load secrets with `wrangler secret` and read them from `env`; do not commit API keys or `.dev.vars` with real values. Confidence: 0.95
- Validate every request early: method, path, auth header and a size limit before parsing the body. Confidence: 0.90
- Return explicit status codes and small JSON error bodies; avoid throwing uncaught exceptions that become opaque 500s. Confidence: 0.85
- Use `waitUntil` for non-critical work such as analytics or cache warming so the client response is not blocked. Confidence: 0.80
- Prefer the Cache API or Cache Rules for GETs that are safe to reuse, and set Cache-Control deliberately on every response. Confidence: 0.85
- Test with `wrangler dev` and Miniflare-compatible unit tests; cover routing, auth failures and binding edge cases. Confidence: 0.85
- Pin compatibility date in Wrangler config and bump it on purpose after reading the runtime changelog. Confidence: 0.85
- Use Durable Objects when you need strong consistency per key (rooms, counters, locks); use KV for eventually consistent reads. Confidence: 0.85
- Stream large responses and uploads when possible; avoid buffering whole files in memory inside the isolate. Confidence: 0.80
- Log with structured JSON fields (request id, route, status, duration) and ship them to your observability sink. Confidence: 0.80
- Gate production deploys behind a staging route or environment, and smoke-test the worker URL before shifting traffic. Confidence: 0.85
- Keep CPU-heavy work short; move bulk transforms and ML to Queues, Workflows or an origin service. Confidence: 0.85
- Prefer fetch to first-party Cloudflare services over stuffing large SDKs into the Worker bundle. Confidence: 0.75
- Review the bundle size on every change; drop unused deps and avoid Node polyfills you do not need. Confidence: 0.80
- Document every binding and its purpose at the top of the Worker entry file so onboarding does not require tribal knowledge. Confidence: 0.75
- Treat cron Triggers and Queue consumers as first-class entrypoints with the same validation and logging standards as HTTP. Confidence: 0.80
Best PracticesPerformanceDevOps+2
F@f
0
Postgres EXPLAIN Slow Query Analyzer
Skill

Reads Postgres EXPLAIN and EXPLAIN ANALYZE plans (text or JSON) and finds why a query is slow - sequential scans on large relations, nested loops with huge row estimates, misestimates (estimated vs actual), high buffer reads, Sort/Hash that spill to disk, missing LIMIT pushdown and expensive nodes by actual time. Ranks fixes (index, rewrite, stats). Offline stdlib Python analyzer.

---
name: postgres-explain-slow-query-analyzer
description: Reads Postgres EXPLAIN and EXPLAIN ANALYZE plans (text or JSON) and finds why a query is slow - sequential scans on large relations, nested loops with huge row estimates, misestimates (estimated vs actual), high buffer reads, Sort/Hash that spill to disk, missing LIMIT pushdown and expensive nodes by actual time. Ranks fixes (index, rewrite, stats). Offline stdlib Python analyzer.
---

# Postgres EXPLAIN Slow Query Analyzer

You help developers and DBAs read Postgres query plans. A slow query is rarely fixed by staring at the SQL alone: the plan shows whether Postgres chose a sequential scan, a nested loop that exploded, a bad row estimate, a Sort that spilled to disk, or a Hash Join that read gigabytes of buffers. You take an `EXPLAIN` or `EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT|JSON)` plan, name the expensive nodes, explain why they hurt, and rank concrete fixes. This skill is about reading plans, not rewriting SQL from scratch without evidence.

You do not run destructive statements. Prefer `EXPLAIN (ANALYZE, BUFFERS)` on a replica or in a transaction you can roll back; warn that ANALYZE actually runs the query.

## Files in this skill

- `scripts/explain_analyze.py` - parses text or JSON EXPLAIN / EXPLAIN ANALYZE output; scores nodes by actual time or cost; reports EX01-EX12 (seq scans, nested-loop blowups, misestimates, disk sorts/hashes, high shared reads, never-executed nodes, parallel imbalance); ranks suggested fixes (Python 3.8+ standard library only)
- `references/plan-nodes-and-buffers.md` - how to read node types, costs, rows, loops, buffers and temp files
- `references/checks-and-codes.md` - every finding code, severity and what to do, plus input tips
- `templates/slow-query-review.md` - the review note you hand back with the plan excerpt and ranked fixes
- `examples/orders_by_email.explain.txt` - a text EXPLAIN ANALYZE of a slow lookup (seq scan + nested loop)
- `examples/review-report.md` - the real analyzer output on the example

## Workflow

### 1. Collect the plan
Ask for Postgres version, the SQL, and an `EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)` (or JSON). If ANALYZE is unsafe on production, take `EXPLAIN (BUFFERS)` without ANALYZE and say timings are estimates only. Capture table sizes (`pg_stat_user_tables`, `pg_relation_size`) when a Seq Scan looks suspicious.

### 2. Run the analyzer
```
python3 scripts/explain_analyze.py examples/orders_by_email.explain.txt
python3 scripts/explain_analyze.py plan.json --json-out
python3 scripts/explain_analyze.py plan.txt --min-ms 5
python3 scripts/explain_analyze.py --self-test
```
Exit 0 = no high findings, 1 = high findings, 2 = bad input. Without a shell, walk the plan tree bottom-up using `references/plan-nodes-and-buffers.md` and apply the codes in `references/checks-and-codes.md`.

### 3. Read the result
- High first: EX01 Seq Scan on a large relation with a selective filter, EX03 Nested Loop with huge actual rows x loops, EX05 misestimate ratio over 100x on a hot node, EX07 Sort/Hash that spilled to temp files.
- Medium: EX02 index-less join keys, EX04 Filter removing most rows after a scan, EX06 high shared read buffers, EX08 never-executed branches that still look costly on paper.
- Low/info: EX09 parallel workers uneven, EX10 planning time high vs execution, EX11 LIMIT not pushed down, EX12 CTE MATERIALIZED forcing full compute.

### 4. Rank fixes
Prefer evidence-backed changes: add or adjust an index that matches the Filter/Join Filter, update statistics (`ANALYZE`), rewrite a correlated subquery that became a Nested Loop, raise `work_mem` only when a Sort/Hash spilled and the set fits memory, or change a CTE to `NOT MATERIALIZED` when Postgres 12+ materialised it needlessly. Do not invent indexes without naming columns from the plan.

### 5. Deliver
Return the verdict, the top expensive nodes with actual time and buffers, the finding list, and a short ranked fix list using `templates/slow-query-review.md`.

## Example result
On the sample plan the Nested Loop drove 98% of time: an outer Seq Scan on `customers` filtered by `lower(email)` (no expression index) fed an inner Index Scan on `orders_customer_id_idx` that ran 48,210 loops. Estimated rows on the outer scan were 42 vs actual 48,210 (misestimate). Shared read buffers were high on `orders`. Ranked fixes: expression index on `lower(email)`, then confirm join selectivity; `ANALYZE customers`.

## Rules

- Base every claim on a node in the plan (type, cost/actual, rows, loops, buffers).
- Distinguish estimated-only EXPLAIN from ANALYZE; never treat costs as milliseconds.
- Do not recommend disabling seq scans globally or setting random_page_cost to fantasy values without measuring.
- Warn that EXPLAIN ANALYZE runs the query (triggers, writes, locks).
- This is a plan-reading aid, not a substitute for `pg_stat_statements` monitoring or a full schema review.
FILE:examples/orders_by_email.explain.txt
QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------
Nested Loop  (cost=0.42..184220.50 rows=12 width=72) (actual time=0.085..912.440 rows=96 loops=1)
  Buffers: shared hit=1204 read=88440
  ->  Seq Scan on public.customers c  (cost=0.00..1850.00 rows=42 width=40) (actual time=0.040..88.200 rows=48210 loops=1)
        Filter: (lower((email)::text) = 'ada@example.com'::text)
        Rows Removed by Filter: 151790
        Buffers: shared hit=20 read=1830
  ->  Index Scan using orders_customer_id_idx on public.orders o  (cost=0.42..4.20 rows=8 width=40) (actual time=0.015..0.016 rows=0 loops=48210)
        Index Cond: (customer_id = c.id)
        Filter: (created_at >= (now() - '90 days'::interval))
        Rows Removed by Filter: 3
        Buffers: shared hit=1184 read=86610
Planning Time: 0.412 ms
Execution Time: 912.610 ms
FILE:examples/review-report.md
# Postgres EXPLAIN analysis

Source: `examples/orders_by_email.explain.txt`
Execution Time: 912.61 ms
Planning Time: 0.412 ms

**Verdict: NEEDS WORK** - 3 high finding(s).

## Top nodes by time (or cost)

| Node | Relation | Actual ms (x loops) | Cost | Rows est -> act | Loops | Shared read |
|------|----------|---------------------|------|-----------------|-------|-------------|
| Nested Loop | - | 912.4 | 184220 | 12 -> 96 | 1 | 88440 |
| Index Scan | public.orders | 771.4 | 4 | 8 -> 0 | 48210 | 86610 |
| Seq Scan | public.customers | 88.2 | 1850 | 42 -> 48210 | 1 | 1830 |

## Findings

| Sev | Code | Detail |
|-----|------|--------|
| high | EX01 | Seq Scan on public.customers with selective Filter ((lower((email)::text) = 'ada@example.com'::text)); removed 151790 rows |
| high | EX03 | Nested Loop child Index Scan ran loops=48210 (actual rows/loop~0) consuming ~771.4 ms |
| high | EX05 | Misestimate on Seq Scan public.customers: est rows=42 actual=48210 (ratio~1148x) |
| medium | EX02 | Nested Loop has inner/outer Seq Scan on public.customers |
| medium | EX06 | Nested Loop ? shared read=88440 blocks |
| medium | EX06 | Index Scan public.orders shared read=86610 blocks |

## Ranked fixes (suggested)

1. Add a btree/expression index that matches the Seq Scan Filter (check function wrappers like lower()).
2. Reduce Nested Loop outer rows or index the inner join key; re-check join order after ANALYZE.
3. Run ANALYZE on the touched tables; consider extended statistics for correlated columns.
4. Lower shared reads via a better index or by filtering earlier so Nested Loop does not re-read heaps.

FILE:references/checks-and-codes.md
# Checks and codes

| Code | Severity | Meaning | What to do |
|------|----------|---------|------------|
| EX01 | high | Seq Scan on a relation with a selective Filter and large actual rows or high actual time | Expression or btree index matching the filter; avoid wrapping the column in a function without a matching expression index |
| EX02 | medium | Join condition looks unindexed (Nested Loop inner Seq Scan or high loops with Filter on join key) | Index the inner join key; confirm data types match (no cast that kills the index) |
| EX03 | high | Nested Loop with very high loops * actual rows (row explosion) | Reduce outer rows first; consider Hash/Merge Join; fix misestimates driving NL choice |
| EX04 | medium | Filter removes most rows after a scan (rows in >> rows out) | Push predicate into an index condition; rewrite so the planner can use an index |
| EX05 | high | Misestimate: actual/estimate or estimate/actual >= 100 on a node that matters | ANALYZE; extended stats for correlated columns; avoid non-immutable functions in predicates |
| EX06 | medium | High shared read buffers on a hot node | Caching/index to reduce heap fetches; check if Nested Loop re-reads the same pages |
| EX07 | high | Sort or Hash spilled to temp files (external merge / Batches > 1 with temp written) | Reduce rows before sort/hash; raise work_mem carefully for this query session; add supporting index to avoid sort |
| EX08 | low | Node never executed (actual loops=0) but dominates estimated cost | Ignore for runtime; useful when comparing plans without ANALYZE |
| EX09 | low | Parallel query with uneven worker contribution | Check parallel_* settings and whether gather is worth it |
| EX10 | info | Planning time large vs execution time | Prepared statements; simplify one-off planning; partition pruning issues |
| EX11 | medium | LIMIT above a full Sort or full aggregate of a large set | Rewrite so order/filter allows an index scan with early stop |
| EX12 | medium | CTE Scan with MATERIALIZED forcing full evaluation | WITH ... AS NOT MATERIALIZED (PG12+) or inline the CTE |

## Input tips
- Text plans: paste the full tree; do not strip indentation.
- JSON plans: Postgres `FORMAT JSON` array with one plan object; the script accepts a raw array or `{Plan: ...}`.
- Optional header lines like `QUERY PLAN` or dashed rules are ignored.
FILE:references/plan-nodes-and-buffers.md
# Plan nodes and buffers

## Capturing a useful plan
```sql
EXPLAIN (ANALYZE, BUFFERS, VERBOSE, FORMAT TEXT) <query>;
-- or
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) <query>;
```
On production prefer a hot standby or wrap writes in a transaction you roll back. `ANALYZE` executes the statement.

## Reading a text node line
Example: `Seq Scan on public.customers  (cost=0.00..1550.00 rows=42 width=64) (actual time=0.020..85.110 rows=48210 loops=1)`
- Node type and relation
- `cost=startup..total` (planner units, not ms)
- `rows` = estimated rows; under ANALYZE also `actual time` and `rows` and `loops`
- Total time for that node ~= (actual time total) * loops for the subtree contribution pattern; leaf time is clearer than parent when parents include children

## Common node types
- **Seq Scan**: read the whole heap. Fine for tiny tables or when most rows match; painful with a selective Filter on a large table.
- **Index Scan / Index Only Scan / Bitmap Heap Scan**: good when selective. Bitmap Heap with many rechecks can still hurt.
- **Nested Loop**: for each outer row, run inner. Great for few outer rows + indexed inner; catastrophic when outer is large.
- **Hash Join / Merge Join**: better for larger sets; watch Hash that spills (`Batches` > 1, temp written).
- **Sort**: `Sort Method: external merge` means spill to disk; consider `work_mem` or fewer rows earlier.
- **Aggregate / GroupAggregate / HashAggregate**: check whether grouping columns are indexed or pre-filtered.
- **CTE Scan**: Postgres 12+ may MATERIALIZE CTEs; can block filter pushdown.
- **Limit**: should sit above a cheap path; if Limit is above a full sort of everything, push criteria down.

## Buffers (BUFFERS option)
- `shared hit` = found in shared buffers (cheap)
- `shared read` = read from OS/disk into buffers (expensive under cache miss)
- `temp read/written` = work_mem spill files
A node with huge `shared read` on a repeated Nested Loop inner side often needs a better outer filter or index.

## Row misestimates
Compare `rows` (estimate) to actual `rows`. Ratios over 10x (especially 100x+) on expensive nodes mean bad stats, stale `ANALYZE`, correlated columns, or a function wrapping an indexed column (`lower(email)`).

## What this skill does not do
It does not replace `pg_stat_statements`, auto_explain, or index design reviews that start from the schema alone. It starts from one plan and explains that plan.
FILE:scripts/explain_analyze.py
#!/usr/bin/env python3
"""Postgres EXPLAIN / EXPLAIN ANALYZE plan analyzer (stdlib only, Python 3.8+).

Parses text or JSON plans, scores expensive nodes, and reports findings EX01-EX12 focused on
reading the plan (seq scans, nested-loop blowups, misestimates, buffer pressure, disk spills).

Usage:
  explain_analyze.py PLAN.txt|.json [--min-ms N] [--json-out]
  explain_analyze.py --self-test
Exit: 0 = no high findings, 1 = high findings, 2 = bad input.
"""
import argparse, json, re, sys

SEV = {"high": 0, "medium": 1, "low": 2, "info": 3}

NODE_RE = re.compile(
    r"^(?P<indent>\s*)(?:->\s*)?(?P<type>.+?)"
    r"(?=\s+using\s+|\s+on\s+|\s*\(cost=)"
    r"(?:\s+using\s+(?P<idx>[\w.]+))?"
    r"(?:\s+on\s+(?P<rel>[\w.]+))?"
    r"(?:\s+(?P<alias>\w+))?"
    r"\s*\(cost=(?P<cstart>[\d.]+)\.\.(?P<ctotal>[\d.]+)\s+rows=(?P<erows>[\d]+)\s+width=(?P<width>[\d]+)\)"
    r"(?:\s*\(actual time=(?P<astart>[\d.]+)\.\.(?P<atotal>[\d.]+)\s+rows=(?P<arows>[\d]+)\s+loops=(?P<loops>[\d]+)\))?"
)
BUF_RE = re.compile(
    r"Buffers:\s*(?:shared hit=(?P<shit>\d+))?"
    r"(?:\s*read=(?P<sread>\d+))?"
    r"(?:.*?temp read=(?P<tread>\d+))?"
    r"(?:.*?written=(?P<twrite>\d+))?",
    re.I,
)
FILTER_RE = re.compile(r"^\s+Filter:\s*(.+)$")
REMOVED_RE = re.compile(r"Rows Removed by Filter:\s*(\d+)")
SORT_RE = re.compile(r"Sort Method:\s*(.+)$", re.I)
HASH_BATCH_RE = re.compile(r"Batches:\s*(\d+)", re.I)
PLAN_TIME_RE = re.compile(r"Planning Time:\s*([\d.]+)\s*ms", re.I)
EXEC_TIME_RE = re.compile(r"Execution Time:\s*([\d.]+)\s*ms", re.I)


class InputError(Exception):
    pass


def parse_text(text):
    lines = text.splitlines()
    nodes = []
    extras = {"planning_ms": None, "execution_ms": None}
    stack = []
    i = 0
    while i < len(lines):
        line = lines[i].rstrip()
        if not line or set(line) <= set("-=") or line.strip() == "QUERY PLAN":
            i += 1
            continue
        m = PLAN_TIME_RE.search(line)
        if m:
            extras["planning_ms"] = float(m.group(1)); i += 1; continue
        m = EXEC_TIME_RE.search(line)
        if m:
            extras["execution_ms"] = float(m.group(1)); i += 1; continue
        m = NODE_RE.match(line)
        if m:
            raw_indent = re.match(r"^(\s*)", line).group(1)
            ind = len(raw_indent)
            node = {
                "type": m.group("type").strip(),
                "rel": m.group("rel"),
                "idx": m.group("idx"),
                "cost_start": float(m.group("cstart")),
                "cost_total": float(m.group("ctotal")),
                "est_rows": int(m.group("erows")),
                "width": int(m.group("width")),
                "act_start": float(m.group("astart")) if m.group("astart") else None,
                "act_total": float(m.group("atotal")) if m.group("atotal") else None,
                "act_rows": int(m.group("arows")) if m.group("arows") else None,
                "loops": int(m.group("loops")) if m.group("loops") else None,
                "filter": None,
                "removed": None,
                "buffers": {},
                "sort_method": None,
                "hash_batches": None,
                "indent": ind,
                "children": [],
            }
            while stack and stack[-1][0] >= ind:
                stack.pop()
            if stack:
                stack[-1][1]["children"].append(node)
            else:
                nodes.append(node)
            stack.append((ind, node))
            j = i + 1
            while j < len(lines):
                pl = lines[j]
                if not pl.strip():
                    break
                if NODE_RE.match(pl) or PLAN_TIME_RE.search(pl) or EXEC_TIME_RE.search(pl):
                    break
                if not pl.startswith(" ") and not pl.startswith("\t"):
                    break
                fm = FILTER_RE.match(pl)
                if fm:
                    node["filter"] = fm.group(1).strip()
                rm = REMOVED_RE.search(pl)
                if rm:
                    node["removed"] = int(rm.group(1))
                bm = BUF_RE.search(pl)
                if bm:
                    node["buffers"] = {k: int(bm.group(k)) for k in ("shit", "sread", "tread", "twrite") if bm.group(k)}
                sm = SORT_RE.search(pl)
                if sm:
                    node["sort_method"] = sm.group(1).strip()
                hb = HASH_BATCH_RE.search(pl)
                if hb:
                    node["hash_batches"] = int(hb.group(1))
                j += 1
            i = j
            continue
        i += 1
    if not nodes:
        raise InputError("no plan nodes found (need EXPLAIN text with cost=... rows=...)")
    return nodes, extras


def parse_json_plan(obj):
    if isinstance(obj, list):
        if not obj:
            raise InputError("empty JSON plan array")
        obj = obj[0]
    if not isinstance(obj, dict):
        raise InputError("JSON plan must be an object or array of objects")
    plan = obj.get("Plan") or obj.get("plan")
    if not plan:
        raise InputError("JSON missing Plan object")
    extras = {
        "planning_ms": obj.get("Planning Time"),
        "execution_ms": obj.get("Execution Time"),
    }

    def conv(p, indent=0):
        node = {
            "type": p.get("Node Type", "Unknown"),
            "rel": p.get("Relation Name") or p.get("Relation"),
            "idx": p.get("Index Name"),
            "cost_start": float(p.get("Startup Cost", 0)),
            "cost_total": float(p.get("Total Cost", 0)),
            "est_rows": int(p.get("Plan Rows", 0)),
            "width": int(p.get("Plan Width", 0)),
            "act_start": p.get("Actual Startup Time"),
            "act_total": p.get("Actual Total Time"),
            "act_rows": p.get("Actual Rows"),
            "loops": p.get("Actual Loops"),
            "filter": p.get("Filter"),
            "removed": p.get("Rows Removed by Filter"),
            "buffers": {},
            "sort_method": p.get("Sort Method"),
            "hash_batches": p.get("Hash Batches") or p.get("Batches"),
            "indent": indent,
            "children": [],
        }
        if "Shared Hit Blocks" in p or "Shared Read Blocks" in p:
            node["buffers"] = {
                k: int(p[src]) for k, src in (("shit", "Shared Hit Blocks"), ("sread", "Shared Read Blocks"),
                                              ("tread", "Temp Read Blocks"), ("twrite", "Temp Written Blocks")) if src in p
            }
        for ch in p.get("Plans") or []:
            node["children"].append(conv(ch, indent + 2))
        return node

    return [conv(plan)], extras


def walk(nodes):
    out = []
    def w(n):
        out.append(n)
        for c in n["children"]:
            w(c)
    for n in nodes:
        w(n)
    return out


def time_ms(n):
    if n["act_total"] is None or n["loops"] is None:
        return None
    return float(n["act_total"]) * float(n["loops"])


def analyze(nodes, extras, min_ms=1.0):
    findings = []
    flat = walk(nodes)

    def add(sev, code, msg, node=None):
        findings.append((sev, code, msg, node))

    for n in flat:
        t = n["type"]
        ms = time_ms(n)
        est, act = n["est_rows"], n["act_rows"]
        loops = n["loops"] or 1
        rel = n["rel"] or "?"

        if t.startswith("Seq Scan") and n.get("filter") and (n.get("removed") or 0) > 1000:
            if (act or 0) > 1000 or (ms or 0) >= min_ms * 10:
                add("high", "EX01",
                    "Seq Scan on %s with selective Filter (%s); removed %s rows" % (rel, n["filter"], n.get("removed")), n)

        if t.startswith("Nested Loop"):
            for c in n["children"]:
                if c["type"].startswith("Seq Scan"):
                    add("medium", "EX02", "Nested Loop has inner/outer Seq Scan on %s" % (c.get("rel") or "?"), c)

        if t.startswith("Nested Loop"):
            for c in n["children"]:
                cl = c.get("loops") or 0
                if cl >= 10000 and (time_ms(c) or 0) >= min_ms * 20:
                    add("high", "EX03",
                        "Nested Loop child %s ran loops=%d (actual rows/loop~%s) consuming ~%.1f ms" % (
                            c["type"], cl, c.get("act_rows"), time_ms(c) or 0), c)

        if n.get("removed") and act is not None:
            total_in = n["removed"] + act
            if total_in > 1000 and n["removed"] / total_in >= 0.9:
                add("medium", "EX04",
                    "Filter on %s %s removes %.0f%% of rows (%d removed, %d kept)" % (
                        t, rel, 100.0 * n["removed"] / total_in, n["removed"], act), n)

        if act is not None and est is not None and (ms or 0) >= min_ms:
            if est == 0:
                ratio = float("inf") if act > 0 else 1.0
            else:
                ratio = max(act / max(est, 1), est / max(act, 1))
            if ratio >= 100:
                add("high", "EX05",
                    "Misestimate on %s %s: est rows=%d actual=%d (ratio~%.0fx)" % (t, rel, est, act, ratio if ratio != float("inf") else 9999), n)

        sread = n.get("buffers", {}).get("sread") or 0
        if sread >= 5000 and (ms or 0) >= min_ms:
            add("medium", "EX06", "%s %s shared read=%d blocks" % (t, rel, sread), n)

        sm = (n.get("sort_method") or "").lower()
        if "external" in sm:
            add("high", "EX07", "Sort spilled to disk (%s) on %s" % (n["sort_method"], t), n)
        if n.get("hash_batches") and n["hash_batches"] > 1 and (n.get("buffers", {}).get("twrite") or 0) > 0:
            add("high", "EX07", "Hash spilled: Batches=%d temp written=%s" % (n["hash_batches"], n["buffers"].get("twrite")), n)

        if loops == 0 and n["cost_total"] >= 1000:
            add("low", "EX08", "Node %s never executed but cost=%.0f" % (t, n["cost_total"]), n)

        if t.startswith("Limit"):
            for c in n["children"]:
                if c["type"].startswith("Sort") and (c.get("act_rows") or c.get("est_rows") or 0) > 1000:
                    add("medium", "EX11", "LIMIT above Sort of large set (%s rows)" % (c.get("act_rows") or c.get("est_rows")), n)

        if "CTE" in t and (ms or n["cost_total"] > 1000):
            add("medium", "EX12", "CTE Scan %s may be materialized; consider NOT MATERIALIZED if filters should push down" % (n.get("rel") or ""), n)

    if extras.get("planning_ms") and extras.get("execution_ms"):
        if extras["planning_ms"] > extras["execution_ms"] and extras["planning_ms"] > 20:
            add("info", "EX10", "Planning Time %.1f ms > Execution Time %.1f ms" % (extras["planning_ms"], extras["execution_ms"]), None)

    findings.sort(key=lambda x: (SEV.get(x[0], 9), x[1]))
    return findings


def report(nodes, extras, findings, src):
    flat = walk(nodes)
    lines = []
    lines.append("# Postgres EXPLAIN analysis")
    lines.append("")
    lines.append("Source: `%s`" % src)
    if extras.get("execution_ms") is not None:
        lines.append("Execution Time: %s ms" % extras["execution_ms"])
    if extras.get("planning_ms") is not None:
        lines.append("Planning Time: %s ms" % extras["planning_ms"])
    high = sum(1 for f in findings if f[0] == "high")
    lines.append("")
    if high:
        lines.append("**Verdict: NEEDS WORK** - %d high finding(s)." % high)
    elif findings:
        lines.append("**Verdict: OK with notes** - %d finding(s), none high." % len(findings))
    else:
        lines.append("**Verdict: OK** - no findings above thresholds.")
    lines.append("")
    lines.append("## Top nodes by time (or cost)")
    lines.append("")
    scored = []
    for n in flat:
        ms = time_ms(n)
        scored.append((ms if ms is not None else -1, n["cost_total"], n))
    scored.sort(key=lambda x: (x[0] if x[0] >= 0 else -1, x[1]), reverse=True)
    lines.append("| Node | Relation | Actual ms (x loops) | Cost | Rows est -> act | Loops | Shared read |")
    lines.append("|------|----------|---------------------|------|-----------------|-------|-------------|")
    for ms, cost, n in scored[:12]:
        am = ("%.1f" % ms) if ms is not None and ms >= 0 else "-"
        ra = "%s -> %s" % (n["est_rows"], n["act_rows"] if n["act_rows"] is not None else "-")
        lines.append("| %s | %s | %s | %.0f | %s | %s | %s |" % (
            n["type"], n["rel"] or "-", am, cost, ra, n["loops"] if n["loops"] is not None else "-",
            n.get("buffers", {}).get("sread", "-")))
    lines.append("")
    lines.append("## Findings")
    lines.append("")
    if not findings:
        lines.append("None.")
    else:
        lines.append("| Sev | Code | Detail |")
        lines.append("|-----|------|--------|")
        for sev, code, msg, _ in findings:
            lines.append("| %s | %s | %s |" % (sev, code, msg.replace("|", "/")))
    lines.append("")
    lines.append("## Ranked fixes (suggested)")
    lines.append("")
    fixes = []
    codes = {f[1] for f in findings}
    if "EX01" in codes:
        fixes.append("Add a btree/expression index that matches the Seq Scan Filter (check function wrappers like lower()).")
    if "EX03" in codes or "EX02" in codes:
        fixes.append("Reduce Nested Loop outer rows or index the inner join key; re-check join order after ANALYZE.")
    if "EX05" in codes:
        fixes.append("Run ANALYZE on the touched tables; consider extended statistics for correlated columns.")
    if "EX07" in codes:
        fixes.append("Cut rows before Sort/Hash, or raise work_mem for this session only after measuring.")
    if "EX06" in codes:
        fixes.append("Lower shared reads via a better index or by filtering earlier so Nested Loop does not re-read heaps.")
    if "EX11" in codes:
        fixes.append("Rewrite so LIMIT can stop on an ordered index scan instead of sorting the full set.")
    if "EX12" in codes:
        fixes.append("Try WITH ... AS NOT MATERIALIZED or inline the CTE so filters push down.")
    if not fixes:
        fixes.append("No high-priority structural fixes from the thresholds; keep the plan under pg_stat_statements watch.")
    for i, f in enumerate(fixes, 1):
        lines.append("%d. %s" % (i, f))
    lines.append("")
    return "\n".join(lines) + "\n"


def load_plan(path):
    raw = open(path, encoding="utf-8").read()
    if path.endswith(".json") or raw.lstrip().startswith(("[", "{")):
        try:
            obj = json.loads(raw)
        except json.JSONDecodeError as e:
            raise InputError("invalid JSON: %s" % e)
        return parse_json_plan(obj)
    return parse_text(raw)


def self_test():
    tests = []
    def t(name, ok):
        tests.append((name, bool(ok)))

    sample = """Nested Loop  (cost=0.42..184220.50 rows=12 width=72) (actual time=0.085..912.440 rows=96 loops=1)
  Buffers: shared hit=1204 read=88440
  ->  Seq Scan on public.customers c  (cost=0.00..1850.00 rows=42 width=40) (actual time=0.040..88.200 rows=48210 loops=1)
        Filter: (lower((email)::text) = 'ada@example.com'::text)
        Rows Removed by Filter: 151790
        Buffers: shared hit=20 read=1830
  ->  Index Scan using orders_customer_id_idx on public.orders o  (cost=0.42..4.20 rows=8 width=40) (actual time=0.015..0.016 rows=0 loops=48210)
        Index Cond: (customer_id = c.id)
        Buffers: shared hit=1184 read=86610
Planning Time: 0.412 ms
Execution Time: 912.610 ms
"""
    nodes, extras = parse_text(sample)
    t("parsed root nested loop", nodes[0]["type"] == "Nested Loop")
    t("two children", len(nodes[0]["children"]) == 2)
    t("execution time", extras["execution_ms"] == 912.610)
    findings = analyze(nodes, extras)
    codes = {f[1] for f in findings}
    t("EX01 seq scan selective", "EX01" in codes)
    t("EX03 nested loop explosion", "EX03" in codes)
    t("EX05 misestimate", "EX05" in codes)
    t("EX06 shared reads", "EX06" in codes)
    r = report(nodes, extras, findings, "t")
    t("report verdict needs work", "NEEDS WORK" in r)

    tiny = """Seq Scan on public.t  (cost=0.00..1.05 rows=5 width=4) (actual time=0.002..0.003 rows=5 loops=1)
Execution Time: 0.020 ms
"""
    nodes2, ex2 = parse_text(tiny)
    f2 = analyze(nodes2, ex2)
    t("tiny table no high", not any(x[0] == "high" for x in f2))

    spill = """Sort  (cost=1000..1100 rows=10000 width=8) (actual time=50..60 rows=10000 loops=1)
  Sort Method: external merge  Disk: 4096kB
"""
    ns, es = parse_text(spill)
    fs = analyze(ns, es)
    t("EX07 external sort", any(x[1] == "EX07" for x in fs))

    j = [{"Plan": {"Node Type": "Limit", "Startup Cost": 0, "Total Cost": 10, "Plan Rows": 10, "Plan Width": 4,
                  "Actual Startup Time": 0.1, "Actual Total Time": 5.0, "Actual Rows": 10, "Actual Loops": 1,
                  "Plans": [{"Node Type": "Sort", "Startup Cost": 0, "Total Cost": 9, "Plan Rows": 5000, "Plan Width": 4,
                             "Actual Startup Time": 0.1, "Actual Total Time": 4.9, "Actual Rows": 5000, "Actual Loops": 1,
                             "Sort Method": "quicksort"}]},
          "Planning Time": 1.0, "Execution Time": 5.1}]
    nj, ej = parse_json_plan(j)
    fj = analyze(nj, ej)
    t("JSON limit+sort -> EX11", any(x[1] == "EX11" for x in fj))

    try:
        parse_text("not a plan")
        ok = False
    except InputError:
        ok = True
    t("bad input rejected", ok)

    for name, ok in tests:
        print(("PASS  " if ok else "FAIL  ") + name)
    passed = sum(ok for _, ok in tests)
    print("%d/%d passed" % (passed, len(tests)))
    return 0 if passed == len(tests) else 1


def main(argv=None):
    ap = argparse.ArgumentParser(description="Analyze Postgres EXPLAIN / EXPLAIN ANALYZE plans.")
    ap.add_argument("plan", nargs="?")
    ap.add_argument("--min-ms", type=float, default=1.0)
    ap.add_argument("--json-out", action="store_true")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args(argv)
    if a.self_test:
        return self_test()
    if not a.plan:
        ap.print_usage(sys.stderr)
        return 2
    try:
        nodes, extras = load_plan(a.plan)
        findings = analyze(nodes, extras, min_ms=a.min_ms)
    except (OSError, InputError) as e:
        print("error: %s" % e, file=sys.stderr)
        return 2
    if a.json_out:
        print(json.dumps({
            "execution_ms": extras.get("execution_ms"),
            "planning_ms": extras.get("planning_ms"),
            "findings": [{"severity": s, "code": c, "detail": m} for s, c, m, _ in findings],
        }, indent=2))
    else:
        sys.stdout.write(report(nodes, extras, findings, a.plan))
    return 1 if any(f[0] == "high" for f in findings) else 0


if __name__ == "__main__":
    sys.exit(main())
FILE:templates/slow-query-review.md
# Slow query plan review

- Date:
- Database / Postgres version:
- Environment (prod replica / staging):
- Query name or ticket:

## SQL (short)
```sql

```

## Verdict
- Overall:
- Dominant time sinks:

## Top nodes
| Node | Actual time / cost | Rows est -> act | Loops | Buffers | Notes |
|------|--------------------|-----------------|-------|---------|-------|
|      |                    |                 |       |         |       |

## Findings
| Code | Severity | Detail |
|------|----------|--------|
|      |          |        |

## Ranked fixes
1.
2.
3.

## Follow-ups
- [ ] Capture `EXPLAIN (ANALYZE, BUFFERS)` after the change
- [ ] Check `pg_stat_user_indexes` / unused indexes before adding more
- [ ] Note whether ANALYZE on base tables was stale
PerformanceDatabaseExplainer+2
F@f
0
Load Testing taste
Taste

Opinionated conventions for planning, running and reading load and performance tests for web services.

# Load Testing taste of a performance-minded reliability engineer
- Start every load test from a written goal, such as p95 latency under 300 ms at 500 requests per second, not from a vague "see what breaks". Confidence: 0.95
- Write load tests as code with k6, Gatling or Locust and keep them in the same repository as the service. Confidence: 0.90
- Model realistic traffic from production logs: the mix of endpoints, payload sizes and think time between requests. Confidence: 0.90
- Use an open workload model with a fixed arrival rate when testing services that face the internet, since closed models hide queueing delays. Confidence: 0.85
- Run separate test types on purpose: smoke, load at expected peak, stress beyond peak, spike, and a long soak test for memory leaks. Confidence: 0.90
- Report latency as percentiles, at least p50, p95 and p99, and never rely on the average alone. Confidence: 0.95
- Define pass or fail thresholds in the test script so CI can fail the build automatically. Confidence: 0.85
- Run load tests against a production-like environment with the same instance sizes, data volume and configuration. Confidence: 0.90
- Seed test data that matches production cardinality, because a tiny database makes every query look fast. Confidence: 0.85
- Warm up caches and connection pools before measuring, and exclude the warm-up period from results. Confidence: 0.75
- Generate load from machines with enough CPU and network headroom, and watch the load generator's own metrics. Confidence: 0.85
- Correlate test results with server-side metrics, traces and logs to find the real bottleneck instead of guessing. Confidence: 0.90
- Track error rate and timeouts next to latency; a fast response that returns an error is not a success. Confidence: 0.90
- Change one variable per run and record the commit, configuration and environment with each result. Confidence: 0.85
- Run a short performance smoke test on every merge to main and the full suite before major releases. Confidence: 0.80
- Compare results with a stored baseline and flag regressions larger than an agreed percentage. Confidence: 0.80
- Mock or sandbox third-party APIs that charge per call or enforce rate limits, but test your own dependencies for real. Confidence: 0.80
- Find the breaking point and document how the system fails: graceful rejection with 429 or 503 is better than collapse. Confidence: 0.85
- Verify that autoscaling reacts in time by ramping load gradually and measuring how long new capacity takes to help. Confidence: 0.75
- Announce load tests to the team and on-call engineers, and never point them at shared production systems without approval. Confidence: 0.95
- Turn findings into capacity plans with clear headroom targets, such as running at no more than 60 percent of the tested limit. Confidence: 0.70
Best PracticesPerformanceMonitoring+2
F@f
0
Unity Game Project taste
Taste

Opinionated conventions for structuring, testing and shipping Unity game projects.

# Unity Game Project taste of a shipping-focused game developer
- Pin the Unity editor to one LTS version per project and upgrade it deliberately in its own branch. Confidence: 0.90
- Use Git with Git LFS for binary assets, plus a .gitattributes file and Unity's smart merge tool for scenes and prefabs. Confidence: 0.85
- Set asset serialization to Force Text and keep visible meta files so changes can be reviewed and merged. Confidence: 0.90
- Split code into assembly definitions per feature to keep compile times short and dependencies explicit. Confidence: 0.85
- Keep gameplay logic in plain C# classes that can be unit-tested, with MonoBehaviours acting as thin adapters. Confidence: 0.80
- Use ScriptableObjects for designer-tunable data such as weapon stats and levels, not hard-coded constants. Confidence: 0.85
- Avoid GameObject.Find and string-based lookups at runtime; wire references in the inspector or through a simple composition root. Confidence: 0.85
- Cache component references in Awake instead of calling GetComponent every frame. Confidence: 0.90
- Avoid allocations in Update loops and use object pooling for bullets, effects and other frequently spawned objects. Confidence: 0.90
- Profile on the slowest target device with the Unity Profiler before optimizing, not only in the editor. Confidence: 0.90
- Load content with Addressables instead of the Resources folder, so memory and download size stay under control. Confidence: 0.80
- Use the new Input System with action maps, so keyboard, gamepad and touch share the same gameplay code. Confidence: 0.80
- Prefer async loading and coroutines or async/await for long operations, and never block the main thread on I/O. Confidence: 0.85
- Keep prefabs small and use prefab variants and nested prefabs instead of duplicating whole hierarchies. Confidence: 0.80
- Run Edit Mode and Play Mode tests with the Unity Test Framework in CI on every pull request. Confidence: 0.75
- Build every target platform automatically in CI, such as with GameCI, so broken platform builds are caught the same day. Confidence: 0.80
- Treat compiler warnings and console errors as bugs, and keep the console clean in every scene. Confidence: 0.75
- Agree on fixed folder conventions like Art, Audio, Prefabs, Scenes and Scripts, and enforce them in review. Confidence: 0.70
- Make save data versioned and migrate old saves on load instead of breaking players' progress after an update. Confidence: 0.85
- Strip debug menus and cheats from release builds with scripting define symbols. Confidence: 0.80
Best PracticesPerformanceGames+1
F@f
0
WebAssembly Module taste
Taste

Opinionated conventions for building fast, small and safe WebAssembly modules with Rust.

# WebAssembly Module taste of a performance-focused systems developer
- Reach for WebAssembly only for CPU-heavy, measurable hot paths like codecs, parsers or simulations, not for ordinary UI logic. Confidence: 0.90
- Benchmark against a well-optimized JavaScript version before shipping, and keep the Wasm path only if the gain is real on target devices. Confidence: 0.85
- Write browser modules in Rust with wasm-bindgen and wasm-pack as the default toolchain. Confidence: 0.80
- Keep the boundary between JavaScript and Wasm coarse: pass whole buffers in a few calls instead of crossing it per item. Confidence: 0.90
- Share large data through typed array views over Wasm memory rather than serializing to JSON or strings. Confidence: 0.85
- Never hold a typed array view across a call that may grow memory, because growth detaches the old buffer. Confidence: 0.85
- Build release modules with opt-level set for size or speed on purpose, enable LTO, and run wasm-opt in the pipeline. Confidence: 0.85
- Track the compressed .wasm size in CI and fail the build when it grows past an agreed budget. Confidence: 0.80
- Load modules with WebAssembly.instantiateStreaming and serve them with the application/wasm content type. Confidence: 0.85
- Run heavy Wasm work in a Web Worker so it never blocks the main thread. Confidence: 0.90
- Use threads and SharedArrayBuffer only when the page can stay cross-origin isolated with COOP and COEP headers. Confidence: 0.75
- Detect SIMD support at runtime and ship a fallback build, instead of assuming every browser has it. Confidence: 0.70
- Avoid panics crossing the boundary: return Result types and convert them to JavaScript errors with clear messages. Confidence: 0.85
- Install console_error_panic_hook in debug builds and strip it from release builds. Confidence: 0.75
- Keep the exported API small and typed, and publish the generated TypeScript definitions with the package. Confidence: 0.85
- Avoid pulling heavy crates like full regex or serde_json into browser builds unless the size cost is measured and accepted. Confidence: 0.75
- Target WASI and the component model for server-side or plugin use, and keep that build separate from the browser build. Confidence: 0.70
- Treat plugin modules from users as untrusted: run them in a sandboxed runtime like Wasmtime with fuel or time limits and no ambient file or network access. Confidence: 0.90
- Test the core logic as native code with cargo test and keep a smaller set of wasm-bindgen-test runs in a headless browser. Confidence: 0.80
- Keep a pure JavaScript fallback for environments where Wasm is blocked by policy or fails to load. Confidence: 0.65
Best PracticesPerformanceFrontend+1
F@f
0
API Rate Limit Policy Simulator
Skill

Simulates API rate limits before you ship them - token bucket, fixed window, sliding log and sliding counter, per client, endpoint, tier or global - against generated or recorded traffic with retrying clients. Shows who gets 429s and for how long, fixed-window boundary bursts, retry herds, noisy neighbours, abusive clients that still get through and peaks over backend capacity. Includes an offline stdlib Python simulator with --self-test.

---
name: api-rate-limit-policy-simulator
description: Simulates API rate limits before you ship them - token bucket, fixed window, sliding log and sliding counter, per client, endpoint, tier or global - against generated or recorded traffic with retrying clients. Shows who gets 429s and for how long, fixed-window boundary bursts, retry herds, noisy neighbours, abusive clients that still get through and peaks over backend capacity. Includes an offline stdlib Python simulator with --self-test.
---

# API Rate Limit Policy Simulator

You help backend and platform engineers choose rate limits with evidence instead of round numbers. A limit that looks safe on paper ("300 per minute per key") can still let 1.8x that through at a window boundary, throttle a mobile app whose thousands of users share one API key, release a herd of retries at the reset second, and do nothing against a scraper that stays just under it. You describe the policies and the traffic in a small JSON file, replay it, and read the result client by client and policy by policy.

## Files in this skill

- `scripts/rate_sim.py` - simulates token bucket, fixed window, sliding log and sliding counter limiters keyed by client, endpoint, client+endpoint or global, scoped to endpoints and client tiers; generates steady, Poisson or burst traffic (or replays a CSV trace), lets clients retry immediately, with backoff or by honouring Retry-After, and reports 429s, delays, failures, worst-case and observed window counts, peaks vs capacity, findings RL01-RL10 and a sample 429 response (Python 3.8+ standard library only)
- `references/algorithms.md` - how each algorithm behaves, its worst case, memory cost and when to pick it
- `references/policy-design.md` - choosing keys, tiers, numbers, headers and client retry rules; what the finding codes mean
- `templates/rate-limit-review.md` - the review to hand back
- `examples/orders-api.json` - a public orders API with a per-key fixed window, a login limit and a global fixed window; five clients including a shared mobile key, a bulk partner, a scraper and a credential stuffer
- `examples/orders-api-report.md` - the real simulator output on that file
- `examples/orders-api-tuned.json` - the same API after the fixes: per-tier token buckets, a global token bucket sized to capacity

## Workflow

### 1. Collect the inputs
Ask for: the limits as configured today or as proposed (algorithm, key, numbers, which endpoints and which clients), where they are enforced (gateway, CDN, app, Redis), the backend capacity in requests per second it can sustain, and the traffic: the biggest legitimate clients and their shape (steady, bursty batch jobs, many users behind one key or one NAT IP), how each one retries, and any abuse seen in logs. Real access logs beat guesses: export `t,client,endpoint` for a busy 5-15 minutes and pass it with `--trace`.

### 2. Run the simulator
```
python3 scripts/rate_sim.py examples/orders-api.json
python3 scripts/rate_sim.py examples/orders-api-tuned.json
python3 scripts/rate_sim.py policies.json --trace access-sample.csv
python3 scripts/rate_sim.py policies.json --json
python3 scripts/rate_sim.py --self-test
```
Exit 0 = no high findings, 1 = high findings (legitimate clients throttled or admitted traffic over capacity), 2 = bad input. Without a shell, reason with `references/algorithms.md`: per key, compare the client's peak per window with the limit, the worst case (2x limit for fixed windows, burst + rate for buckets) with capacity, and think through what each client does after a 429.

### 3. Read the result
- Legit clients first (RL01): any failed or delayed requests, and how long they waited. One key shared by an app's users needs its own tier or a per-user key.
- Capacity (RL03): the peak admitted second vs what the backend sustains. A global limit is the only thing that protects capacity; per-key limits multiply by the number of keys.
- Shape (RL04, RL10): fixed windows let bursts through at boundaries and hand out a whole window at once; retries without jitter all come back in the same second.
- Abuse (RL02): a scraper under the per-key limit is not stopped by limits; it needs detection, auth or a per-endpoint limit.
- Retries (RL05): attempts per logical request above 1.5 means the clients amplify load when throttled.

### 4. Tune and re-run
Change one thing at a time and re-run with the same traffic: switch fixed windows to token buckets or sliding counters, add tiers with `clients` / `exclude_clients`, size the global bucket to capacity (rate = sustainable rps, burst = what the backend absorbs for a second), add endpoint limits for login and expensive calls, and agree pacing with batch partners. Use `references/policy-design.md` for the numbers.

### 5. Deliver
Fill `templates/rate-limit-review.md`: verdict, a before/after table per client, the policy changes as config, the 429 response and headers, client guidance (Retry-After, backoff with jitter, max retries) and what to monitor after rollout.

## Example result
On `examples/orders-api.json` the shared `mobile-app` key hits the 300/minute per-key window: 1,042 of its 1,839 requests succeed only after waiting up to 60 s (RL01, high). Honouring Retry-After without jitter releases 289 retries in second 240, so admitted traffic peaks at 313 req/s against a capacity of 80 (RL03, RL10). The per-key fixed window lets 544 requests through in one rolling minute (1.8x, RL04), and the scraper still gets 45% of its calls through while its immediate retries push it to 2.67 attempts per request. The login limit stops the credential stuffer (40 of 480). In `examples/orders-api-tuned.json` (tier token buckets, global bucket 50 req/s + 30 burst, partner pacing at 2 req/s) legit clients see no 429s, the peak is 27 req/s and only the scraper findings remain.

## Rules

- Simulate with the traffic you actually have (or a trace), not an average; bursts and retries are where limits fail.
- Never call a limit safe for capacity unless a global limit bounds the total.
- Treat delayed requests of legitimate clients as harm, not as success.
- Always return 429 with Retry-After, add jitter, and tell clients how to back off.
- Rate limits are not abuse protection on their own; say when authentication, bot detection or WAF rules are needed.
- Results are a model: confirm with gateway metrics after rollout and keep the limits in config, not code.
FILE:references/algorithms.md
# Rate limit algorithms

| Algorithm | Admits | Worst case in one window | Memory per key | Good for |
|---|---|---|---|---|
| Token bucket (GCRA) | while tokens remain; refills at `rate`/s up to `burst` | burst + rate x window | 2 numbers | most APIs: smooth average, bounded bursts |
| Fixed window | `limit` per calendar window, counter resets | 2 x limit (end of one window + start of next) | 1 counter | quotas and billing ("10,000 per day"), not capacity |
| Sliding log | at most `limit` in any rolling window | limit (exact) | one timestamp per request | small limits: login, OTP, password reset |
| Sliding counter | previous window weighted by overlap + current | about limit (assumes even spread) | 2 counters | large limits where exactness is not needed |

## Token bucket
- `rate` is the long-run average; `burst` is how many calls can arrive at once after a quiet period.
- `limit` + `window_s` without a burst means rate = limit/window and burst = limit: a client can spend the whole minute in one second. Set the burst explicitly.
- Retry-After = (cost - tokens) / rate: usually well under a second, so retries spread out by themselves.
- GCRA (used by many gateways) stores one timestamp and gives the same admit/reject decisions.

## Fixed window
- Cheap (`INCR` + `EXPIRE` in Redis) and easy to explain, so it is everywhere.
- A client can send `limit` in the last second of a window and `limit` again in the first second of the next.
- Every throttled client gets Retry-After = time to the reset, so they all come back in the same second (retry herd).
- Use it for quotas that match business periods; put a token bucket in front of it for capacity.

## Sliding log
- Exact, but stores every admitted timestamp for the window: 10,000/hour per key = 10,000 entries per key.
- Retry-After = oldest relevant entry + window - now: can be long; tell the client.

## Sliding counter
- Estimate = previous count x (1 - elapsed/window) + current count.
- Error comes from uneven traffic: a burst at the end of the previous window is under-counted later (in the simulator's self-test, 10 requests at the very end of one window plus an even trickle later admit 16 in one rolling minute for a limit of 10).
- Good default for large per-key limits behind a token bucket.

## Concurrency limits (not simulated)
Limits on in-flight requests protect slow endpoints better than rate limits; combine with a rate limit for fairness.
FILE:references/policy-design.md
# Designing rate limit policies

## Pick the key
- **API key / token** for authenticated traffic. Watch for keys shared by many users (mobile apps, SDKs embedded in customer sites): give them a tier or move to per-user keys.
- **User or account id** behind the key when the API knows it; fairer than the key.
- **IP** only for anonymous endpoints; offices, schools, carriers and VPNs put thousands of users behind one IP (CGNAT). Use generous IP limits and stricter account limits.
- **Endpoint** for expensive calls (search, export, bulk) and sensitive ones (login, OTP, password reset).
- **Global** to protect capacity. Without it, per-key limits x number of keys is the real ceiling.

## Pick the numbers
1. Sustained rate per key: p99 of a normal busy client's requests per second x 2-3 headroom.
2. Burst: the largest legitimate batch (page load fan-out, sync job) that must not be throttled.
3. Global: rate = what the backend sustains at acceptable latency (load test), burst = what it absorbs for about a second.
4. Login/OTP: 5-10 per minute per account and per IP, sliding log, plus lockout or CAPTCHA after repeated failures.
5. Quotas (per day/month) are a product decision; keep them separate from capacity limits.

## Tiers
Scope policies with `clients` and `exclude_clients` in the simulator; in production map tiers to plans or key metadata (free, paid, partner, internal). Internal services should usually bypass public limits but stay under the global one.

## Responses and headers
- 429 Too Many Requests, `Retry-After` in seconds, a problem+json body naming the limit.
- Advertise the policy: the IETF httpapi ratelimit-headers draft defines `RateLimit-Policy` and `RateLimit` fields (field syntax changed between drafts); many gateways still send `X-RateLimit-Limit`, `-Remaining`, `-Reset`. Pick one and document it.
- Add 0-20% random jitter to Retry-After for fixed windows so throttled clients do not return together.
- Use 503 + Retry-After for overload (global limit), 429 for per-client limits, so clients can tell them apart.

## Client rules to publish
Honour Retry-After; otherwise exponential backoff with full jitter (1, 2, 4 s ...), at most 3-5 retries, never retry non-idempotent calls without an idempotency key; pace batch jobs instead of bursting.

## Finding codes (rate_sim.py)
| Code | Meaning |
|---|---|
| RL01 | legit client failed or delayed (high above 1% of its requests) |
| RL02 | abusive client still gets more than 25% through |
| RL03 | admitted peak over capacity, or no global limit to bound it |
| RL04 | fixed window let more than the limit through in a rolling window |
| RL05 | client retries amplify attempts 1.5x or more |
| RL06 | noisy neighbour holds most of a global limit while legit clients are rejected |
| RL07 | sliding log with a very large limit (memory) |
| RL08 | reminder: 429 + Retry-After and documented limits |
| RL09 | policy never triggers and is 10x above the busiest key |
| RL10 | retry herd: most of the peak second are retries released together |
FILE:templates/rate-limit-review.md
# Rate limit review: <service>

**Scope:** <endpoints / gateway>   **Capacity:** <80 req/s sustained>   **Traffic used:** <generated from ... / trace of 10 min on ...>
**Verdict:** <ship / ship with changes / do not ship>

## What happens today
| Client | Kind | Requests | 429s | OK after retry | Failed | Max wait | Main policy |
|---|---|---|---|---|---|---|---|
| <mobile-app> | <legit> | <1,839> | <1,081> | <1,042> | <0> | <60 s> | <per-key minute> |

Peak admitted: <313 req/s in second 240> vs capacity <80>.

## Findings
1. <HIGH RL01 - shared mobile key throttled; 57% of requests delayed up to 60 s>
2. <HIGH RL03 / MEDIUM RL10 - retry herd at window reset, 4x capacity>
3. <MEDIUM RL04 - fixed window 1.8x at boundary>
4. <MEDIUM RL02 - scraper under the per-key limit>

## Proposed policies
```json
<policies block from the tuned config>
```

## After the change (same traffic)
| Client | 429s before | 429s after | Failed before | Failed after |
|---|---|---|---|---|
| <...> | | | | |

Peak admitted after: <27 req/s>.

## Response contract
- 429 + Retry-After (+ jitter) for per-client limits; 503 + Retry-After for global overload
- Headers: <RateLimit-Policy / RateLimit or X-RateLimit-*>
- Client guidance: <honour Retry-After, backoff with jitter, max 3 retries, pace batch jobs>

## Outside rate limits
<bot detection / auth / WAF rule for the scraper; lockout or CAPTCHA for login>

## Monitor after rollout
<429 rate per client and policy, top throttled keys, p99 latency, admitted rps vs capacity; review in 2 weeks>
FILE:examples/orders-api.json
{
  "service": "Orders API (public v2)",
  "duration_s": 300,
  "capacity_rps": 80,
  "seed": 7,
  "policies": [
    {"name": "per-key minute", "algorithm": "fixed_window", "key": "client", "limit": 300, "window_s": 60},
    {"name": "login", "algorithm": "sliding_log", "key": "client", "limit": 10, "window_s": 60,
     "endpoints": ["/v2/login"]},
    {"name": "global", "algorithm": "fixed_window", "key": "global", "limit": 3600, "window_s": 60}
  ],
  "clients": [
    {"name": "mobile-app", "kind": "legit", "pattern": "poisson", "rps": 6, "endpoint": "/v2/orders",
     "retry": "honor"},
    {"name": "partner-erp", "kind": "legit", "pattern": "burst", "burst": 120, "every_s": 60, "start": 58,
     "endpoint": "/v2/orders/bulk", "retry": "backoff"},
    {"name": "checkout-web", "kind": "legit", "pattern": "poisson", "rps": 3, "endpoint": "/v2/checkout",
     "retry": "honor"},
    {"name": "price-scraper", "kind": "abusive", "pattern": "steady", "rps": 12, "start": 20,
     "endpoint": "/v2/products", "retry": "immediate"},
    {"name": "cred-stuffer", "kind": "abusive", "pattern": "steady", "rps": 2, "start": 60,
     "endpoint": "/v2/login"}
  ]
}
FILE:examples/orders-api-report.md
# Rate limit simulation: Orders API (public v2)

Simulated 300s, 7227 logical requests, 4930 admitted, peak 313 req/s admitted (second 240) vs capacity 80.

**Verdict: 2 high finding(s) - fix before shipping these limits**

## Clients

| Client | Kind | Requests | Attempts | Allowed | 429s | OK after retry | Failed | Failed % | Max Retry-After | Top policy |
|---|---|---|---|---|---|---|---|---|---|---|
| price-scraper | abusive | 3360 | 8961 | 1503 | 7458 | 15 | 1857 | 55.3% | 35.2s | per-key minute |
| mobile-app | legit | 1839 | 2920 | 1839 | 1081 | 1042 | 0 | 0.0% | 59.9s | per-key minute |
| checkout-web | legit | 948 | 948 | 948 | 0 | 0 | 0 | 0.0% | 0s | - |
| partner-erp | legit | 600 | 600 | 600 | 0 | 0 | 0 | 0.0% | 0s | - |
| cred-stuffer | abusive | 480 | 480 | 40 | 440 | 0 | 440 | 91.7% | 55s | login |

## Policies

| Policy | Algorithm | Key | Scope | Sustained | Worst case / window | Busiest key / window | Checks | Rejects |
|---|---|---|---|---|---|---|---|---|
| per-key minute | fixed_window | client | all | 5 req/s | 600 per 60s | 544 | 13909 | 8539 |
| login | sliding_log | client | /v2/login | 0.167 req/s | 10 per 60s | 10 | 480 | 440 |
| global | fixed_window | global | all | 60 req/s | 7200 per 60s | 1235 | 13909 | 0 |

## Findings

- **HIGH RL01** Legit client mobile-app is throttled on 56.7% of its requests (0 failed, 1042 only after retrying, waits up to 59.9s), mostly by policy 'per-key minute'; raise that limit or give this client its own tier.
- **HIGH RL03** Admitted traffic peaks at 313 req/s (second 240) over the backend capacity of 80 req/s; add or lower a global limit.
- **MEDIUM RL02** Abusive client price-scraper still gets 45% of its requests through (1503); tighten the per-client limit or add a stricter policy for its pattern.
- **MEDIUM RL04** Fixed window 'per-key minute' let 544 requests through in one rolling 60s window (limit 300, 1.8x) across a window boundary; use sliding_counter or a token bucket if the limit protects capacity.
- **MEDIUM RL05** Client price-scraper sends 2.67x attempts per logical request because it retries throttled calls; retries count against the limit and add load - require Retry-After or backoff with jitter.
- **MEDIUM RL05** Client mobile-app sends 1.59x attempts per logical request because it retries throttled calls; retries count against the limit and add load - require Retry-After or backoff with jitter.
- **MEDIUM RL10** Retry herd: 289 of the 313 requests admitted in second 240 are retries released by the same Retry-After / window reset; add jitter to Retry-After (or client backoff) and prefer a token bucket or sliding window so capacity is not handed out all at once.
- **INFO RL08** Return 429 with Retry-After on every rejection (see the sample headers) and document the limits so clients can pace themselves.

## Sample 429 (first rejection, t=45.0s, price-scraper /v2/products)

```
HTTP/1.1 429 Too Many Requests
Retry-After: 15
RateLimit-Policy: "per-key minute";q=300;w=60
RateLimit: "per-key minute";r=0;t=15
Content-Type: application/problem+json
```
Header names follow the IETF httpapi ratelimit-headers draft; older gateways use X-RateLimit-Limit / -Remaining / -Reset instead.
FILE:examples/orders-api-tuned.json
{
  "service": "Orders API (public v2, tuned)",
  "notes": "Same traffic as orders-api.json except partner-erp, which agreed to pace its bulk sync at 2 req/s instead of 120-request bursts. Token buckets per tier, a global token bucket sized to capacity.",
  "duration_s": 300,
  "capacity_rps": 80,
  "seed": 7,
  "policies": [
    {"name": "default key", "algorithm": "token_bucket", "key": "client", "rate": 4, "burst": 40,
     "exclude_clients": ["mobile-app", "partner-erp"]},
    {"name": "mobile tier", "algorithm": "token_bucket", "key": "client", "rate": 15, "burst": 60,
     "clients": ["mobile-app"]},
    {"name": "partner tier", "algorithm": "token_bucket", "key": "client", "rate": 3, "burst": 20,
     "clients": ["partner-erp"]},
    {"name": "login", "algorithm": "sliding_log", "key": "client", "limit": 10, "window_s": 60,
     "endpoints": ["/v2/login"]},
    {"name": "global", "algorithm": "token_bucket", "key": "global", "rate": 50, "burst": 30}
  ],
  "clients": [
    {"name": "mobile-app", "kind": "legit", "pattern": "poisson", "rps": 6, "endpoint": "/v2/orders",
     "retry": "honor"},
    {"name": "partner-erp", "kind": "legit", "pattern": "steady", "rps": 2, "start": 58,
     "endpoint": "/v2/orders/bulk", "retry": "backoff"},
    {"name": "checkout-web", "kind": "legit", "pattern": "poisson", "rps": 3, "endpoint": "/v2/checkout",
     "retry": "honor"},
    {"name": "price-scraper", "kind": "abusive", "pattern": "steady", "rps": 12, "start": 20,
     "endpoint": "/v2/products", "retry": "immediate"},
    {"name": "cred-stuffer", "kind": "abusive", "pattern": "steady", "rps": 2, "start": 60,
     "endpoint": "/v2/login"}
  ]
}
FILE:scripts/rate_sim.py
#!/usr/bin/env python3
"""API rate limit policy simulator (Python 3.8+ standard library only).

Replays generated or recorded traffic against one or more rate limit policies and shows who
gets throttled, why, for how long, and whether the policies protect the backend without
hurting legitimate clients.

Algorithms (per policy):
  token_bucket     rate (tokens/s) + burst (bucket size); or limit + window_s (rate = limit/window_s,
                   burst defaults to limit). GCRA behaves the same for admit/reject.
  fixed_window     limit requests per window_s, counter resets on window boundaries
                   (allows up to 2 x limit across a boundary)
  sliding_log      exact: at most limit requests in any window_s (stores one timestamp per request)
  sliding_counter  approximation: previous window weighted by overlap + current window (Cloudflare /
                   Redis style, about limit per rolling window, a few % error)

Config JSON:
{
  "service": "Orders API", "duration_s": 300, "capacity_rps": 60, "seed": 7,
  "policies": [
    {"name": "per-client burst", "algorithm": "token_bucket", "key": "client", "rate": 5, "burst": 20},
    {"name": "per-client minute", "algorithm": "fixed_window", "key": "client", "limit": 200, "window_s": 60},
    {"name": "login", "algorithm": "sliding_log", "key": "client", "limit": 5, "window_s": 60,
     "endpoints": ["/login"]},
    {"name": "global", "algorithm": "sliding_counter", "key": "global", "limit": 3000, "window_s": 60}
  ],
  "clients": [
    {"name": "mobile-app", "kind": "legit", "pattern": "steady", "rps": 2, "endpoint": "/orders"},
    {"name": "nightly-sync", "kind": "legit", "pattern": "burst", "burst": 40, "every_s": 60, "start": 5},
    {"name": "scraper", "kind": "abusive", "pattern": "poisson", "rps": 25, "retry": "immediate"}
  ]
}
  key        client | endpoint | client+endpoint | global
  endpoints  optional list: the policy applies only to these endpoints (prefix match)
  clients / exclude_clients   optional lists: apply only to / skip these clients (tiers, allow lists)
  pattern    steady (rps) | poisson (rps, seeded) | burst (burst requests every every_s seconds)
  start, duration   seconds (default 0 and duration_s); cost = tokens per request (default 1)
  retry      none (default) | immediate (0.1 s later) | backoff (1, 2, 4 s) | honor (Retry-After);
             max_retries default 3
  kind       legit | abusive | unknown - used to judge false positives and leakage

Recorded traffic instead of generated: --trace trace.csv with columns t,client[,endpoint][,cost]
(t in seconds from start). Clients in the config then only add kind/retry information.

Usage:
  python3 rate_sim.py config.json [--trace trace.csv] [--json]
  python3 rate_sim.py --self-test
Exit codes: 0 = no high findings, 1 = high findings (legit clients throttled or backend over
capacity), 2 = bad input.
"""
import argparse
import csv
import heapq
import json
import math
import random
import sys
from collections import defaultdict, deque

ALGOS = ("token_bucket", "fixed_window", "sliding_log", "sliding_counter")
KEYS = ("client", "endpoint", "client+endpoint", "global")


class InputError(ValueError):
    pass


# ----------------------------------------------------------------------------- limiters
class TokenBucket:
    def __init__(self, rate, burst):
        self.rate, self.burst = float(rate), float(burst)
        self.state = {}

    def check(self, key, t, cost):
        tokens, last = self.state.get(key, (self.burst, t))
        tokens = min(self.burst, tokens + (t - last) * self.rate)
        self.state[key] = (tokens, t)
        if tokens + 1e-9 >= cost:
            return True, 0.0, tokens
        return False, (cost - tokens) / self.rate, tokens

    def consume(self, key, t, cost):
        tokens, last = self.state[key]
        self.state[key] = (tokens - cost, t)


class FixedWindow:
    def __init__(self, limit, window):
        self.limit, self.window = float(limit), float(window)
        self.state = {}

    def check(self, key, t, cost):
        w = math.floor(t / self.window)
        start, count = self.state.get(key, (w, 0.0))
        if start != w:
            start, count = w, 0.0
        self.state[key] = (start, count)
        if count + cost <= self.limit + 1e-9:
            return True, 0.0, self.limit - count
        return False, (w + 1) * self.window - t, self.limit - count

    def consume(self, key, t, cost):
        start, count = self.state[key]
        self.state[key] = (start, count + cost)


class SlidingLog:
    def __init__(self, limit, window):
        self.limit, self.window = float(limit), float(window)
        self.state = defaultdict(deque)

    def check(self, key, t, cost):
        log = self.state[key]
        while log and log[0] <= t - self.window:
            log.popleft()
        used = len(log)
        if used + cost <= self.limit + 1e-9:
            return True, 0.0, self.limit - used
        need = int(used + cost - self.limit)  # entries that must expire first
        idx = min(max(need - 1, 0), used - 1) if used else 0
        wait = (log[idx] + self.window - t) if used else self.window
        return False, max(wait, 0.001), self.limit - used

    def consume(self, key, t, cost):
        for _ in range(int(round(cost))):
            self.state[key].append(t)


class SlidingCounter:
    def __init__(self, limit, window):
        self.limit, self.window = float(limit), float(window)
        self.state = {}

    def _roll(self, key, t):
        w = math.floor(t / self.window)
        start, prev, curr = self.state.get(key, (w, 0.0, 0.0))
        if w == start + 1:
            start, prev, curr = w, curr, 0.0
        elif w > start + 1:
            start, prev, curr = w, 0.0, 0.0
        self.state[key] = (start, prev, curr)
        return start, prev, curr

    def check(self, key, t, cost):
        start, prev, curr = self._roll(key, t)
        e = t - start * self.window
        est = prev * (1 - e / self.window) + curr
        if est + cost <= self.limit + 1e-9:
            return True, 0.0, self.limit - est
        lim, w = self.limit, self.window
        if curr + cost <= lim and prev > 0:
            wait = w * (1 - (lim - curr - cost) / prev) - e
        else:
            x = 0.0
            if curr > 0 and lim - cost < curr:
                x = w * (1 - (lim - cost) / curr)
            wait = (w - e) + max(0.0, x)
        return False, max(wait, 0.001), self.limit - est

    def consume(self, key, t, cost):
        start, prev, curr = self.state[key]
        self.state[key] = (start, prev, curr + cost)


def make_limiter(p):
    algo = p["algorithm"]
    if algo == "token_bucket":
        return TokenBucket(p["rate"], p["burst"])
    if algo == "fixed_window":
        return FixedWindow(p["limit"], p["window_s"])
    if algo == "sliding_log":
        return SlidingLog(p["limit"], p["window_s"])
    return SlidingCounter(p["limit"], p["window_s"])


# ----------------------------------------------------------------------------- config
def num(v, what, positive=True):
    try:
        x = float(v)
    except (TypeError, ValueError):
        raise InputError("%s must be a number, got %r" % (what, v))
    if positive and x <= 0:
        raise InputError("%s must be > 0, got %r" % (what, v))
    return x


def normalize(cfg):
    if not isinstance(cfg, dict):
        raise InputError("config must be a JSON object")
    pols = cfg.get("policies")
    if not pols:
        raise InputError("config needs a non-empty 'policies' list")
    out = []
    for i, p in enumerate(pols, 1):
        q = dict(p)
        q.setdefault("name", "policy-%d" % i)
        algo = q.get("algorithm")
        if algo not in ALGOS:
            raise InputError("policy %r: algorithm must be one of %s" % (q["name"], ", ".join(ALGOS)))
        q.setdefault("key", "client")
        if q["key"] not in KEYS:
            raise InputError("policy %r: key must be one of %s" % (q["name"], ", ".join(KEYS)))
        if algo == "token_bucket":
            if "rate" in q:
                q["rate"] = num(q["rate"], q["name"] + ".rate")
                q["burst"] = num(q.get("burst", max(1.0, q["rate"])), q["name"] + ".burst")
            elif "limit" in q:
                lim = num(q["limit"], q["name"] + ".limit")
                win = num(q.get("window_s", 1), q["name"] + ".window_s")
                q["rate"] = lim / win
                q["burst"] = num(q.get("burst", lim), q["name"] + ".burst")
            else:
                raise InputError("policy %r: token_bucket needs rate (+burst) or limit + window_s" % q["name"])
            q.setdefault("window_s", 1.0)
            q["window_s"] = num(q["window_s"], q["name"] + ".window_s")
        else:
            q["limit"] = num(q.get("limit"), q["name"] + ".limit")
            q["window_s"] = num(q.get("window_s"), q["name"] + ".window_s")
        q["endpoints"] = list(q.get("endpoints") or [])
        q["clients"] = list(q.get("clients") or [])
        q["exclude_clients"] = list(q.get("exclude_clients") or [])
        out.append(q)
    cfg = dict(cfg)
    cfg["policies"] = out
    cfg["duration_s"] = num(cfg.get("duration_s", 300), "duration_s")
    if cfg.get("capacity_rps") is not None:
        cfg["capacity_rps"] = num(cfg["capacity_rps"], "capacity_rps")
    clients = []
    for i, c in enumerate(cfg.get("clients") or [], 1):
        c = dict(c)
        c.setdefault("name", "client-%d" % i)
        c.setdefault("kind", "unknown")
        c.setdefault("pattern", "steady")
        c.setdefault("endpoint", "/")
        c.setdefault("retry", "none")
        if c["retry"] not in ("none", "immediate", "backoff", "honor"):
            raise InputError("client %r: retry must be none, immediate, backoff or honor" % c["name"])
        c["max_retries"] = int(c.get("max_retries", 3))
        c["cost"] = num(c.get("cost", 1), c["name"] + ".cost")
        c["start"] = num(c.get("start", 0), c["name"] + ".start", positive=False)
        c["duration"] = num(c.get("duration", cfg["duration_s"] - c["start"]), c["name"] + ".duration")
        if c["pattern"] in ("steady", "poisson"):
            c["rps"] = num(c.get("rps"), c["name"] + ".rps")
        elif c["pattern"] == "burst":
            c["burst"] = int(num(c.get("burst"), c["name"] + ".burst"))
            c["every_s"] = num(c.get("every_s", 60), c["name"] + ".every_s")
        else:
            raise InputError("client %r: pattern must be steady, poisson or burst" % c["name"])
        clients.append(c)
    cfg["clients"] = clients
    return cfg


def generate(cfg):
    rng = random.Random(cfg.get("seed", 1))
    reqs = []
    for c in cfg["clients"]:
        t0, t1 = c["start"], c["start"] + c["duration"]
        if c["pattern"] == "steady":
            n = int(round(c["duration"] * c["rps"]))
            reqs += [(t0 + i / c["rps"], c["name"], c["endpoint"], c["cost"]) for i in range(n)]
        elif c["pattern"] == "poisson":
            t = t0 + rng.expovariate(c["rps"])
            while t < t1:
                reqs.append((t, c["name"], c["endpoint"], c["cost"]))
                t += rng.expovariate(c["rps"])
        else:
            t = t0
            while t < t1:
                reqs += [(t + k * 0.001, c["name"], c["endpoint"], c["cost"]) for k in range(c["burst"])]
                t += c["every_s"]
    return reqs


def read_trace(path):
    reqs = []
    with open(path, newline="", encoding="utf-8") as f:
        for n, row in enumerate(csv.DictReader(f), 2):
            try:
                reqs.append((float(row["t"]), row["client"].strip(), (row.get("endpoint") or "/").strip(),
                             float(row.get("cost") or 1)))
            except (KeyError, ValueError, AttributeError):
                raise InputError("%s line %d: need t,client[,endpoint][,cost]" % (path, n))
    return reqs


# ----------------------------------------------------------------------------- simulation
def policy_key(p, client, endpoint):
    if p["endpoints"] and not any(endpoint.startswith(e) for e in p["endpoints"]):
        return None
    if (p["clients"] and client not in p["clients"]) or client in p["exclude_clients"]:
        return None
    return {"client": client, "endpoint": endpoint, "client+endpoint": client + " " + endpoint,
            "global": "*"}[p["key"]]


def simulate(cfg, reqs):
    pols = cfg["policies"]
    lims = [make_limiter(p) for p in pols]
    cinfo = {c["name"]: c for c in cfg["clients"]}
    heap = []
    for i, (t, cl, ep, cost) in enumerate(sorted(reqs)):
        heapq.heappush(heap, (t, i, cl, ep, cost, 0, i))
    seq = len(reqs)
    stats = defaultdict(lambda: {"logical": 0, "attempts": 0, "allowed": 0, "rejected": 0, "failed": 0, "delayed": 0,
                                 "max_retry_after": 0.0, "blocked_by": defaultdict(int), "first_reject": None})
    pstats = [{"checks": 0, "rejects": 0, "allowed_times": defaultdict(list), "by_client": defaultdict(int)}
              for _ in pols]
    admitted = []
    sample = None
    while heap:
        t, _, cl, ep, cost, attempt, lid = heapq.heappop(heap)
        s = stats[cl]
        if attempt == 0:
            s["logical"] += 1
        s["attempts"] += 1
        keys = [policy_key(p, cl, ep) for p in pols]
        rejecting, wait, remain = [], 0.0, {}
        for j, (lim, k) in enumerate(zip(lims, keys)):
            if k is None:
                continue
            pstats[j]["checks"] += 1
            ok, w, rem = lim.check(k, t, cost)
            remain[j] = rem
            if not ok:
                rejecting.append(j)
                wait = max(wait, w)
        if not rejecting:
            for j, (lim, k) in enumerate(zip(lims, keys)):
                if k is not None:
                    lim.consume(k, t, cost)
                    pstats[j]["allowed_times"][k].append(t)
            s["allowed"] += 1
            if attempt:
                s["delayed"] += 1
            admitted.append((t, cl, attempt))
            continue
        s["rejected"] += 1
        s["max_retry_after"] = max(s["max_retry_after"], wait)
        if s["first_reject"] is None:
            s["first_reject"] = t
        s["blocked_by"][pols[rejecting[0]]["name"]] += 1
        for j in rejecting:
            pstats[j]["rejects"] += 1
            pstats[j]["by_client"][cl] += 1
        if sample is None:
            j = rejecting[0]
            sample = {"t": round(t, 3), "client": cl, "endpoint": ep, "policy": pols[j]["name"],
                      "retry_after": max(1, math.ceil(wait)), "quota": pols[j].get("limit", pols[j].get("burst")),
                      "window_s": pols[j]["window_s"]}
        c = cinfo.get(cl, {})
        mode, maxr = c.get("retry", "none"), c.get("max_retries", 3)
        if mode != "none" and attempt < maxr:
            delay = {"immediate": 0.1, "backoff": 2.0 ** attempt, "honor": wait + 0.05}[mode]
            seq += 1
            heapq.heappush(heap, (t + delay, seq, cl, ep, cost, attempt + 1, lid))
        else:
            s["failed"] += 1
    return stats, pstats, admitted, sample


def max_in_window(times, w):
    best, dq = 0, deque()
    for t in sorted(times):
        dq.append(t)
        while dq[0] <= t - w:
            dq.popleft()
        best = max(best, len(dq))
    return best


def theoretical_max(p):
    w = p["window_s"]
    if p["algorithm"] == "token_bucket":
        return p["burst"] + p["rate"] * w
    if p["algorithm"] == "fixed_window":
        return 2 * p["limit"]
    return p["limit"]


def sustained_rps(p):
    return p["rate"] if p["algorithm"] == "token_bucket" else p["limit"] / p["window_s"]


# ----------------------------------------------------------------------------- analysis
def analyse(cfg, reqs):
    stats, pstats, admitted, sample = simulate(cfg, reqs)
    pols = cfg["policies"]
    kinds = {c["name"]: c["kind"] for c in cfg["clients"]}
    findings = []

    def add(sev, code, msg):
        findings.append({"severity": sev, "code": code, "message": msg})

    per_sec = defaultdict(int)
    retry_sec = defaultdict(int)
    for t, _, att in admitted:
        per_sec[int(t)] += 1
        if att:
            retry_sec[int(t)] += 1
    peak_rps = max(per_sec.values()) if per_sec else 0
    peak_sec = max(per_sec, key=per_sec.get) if per_sec else 0

    clients = []
    for name in sorted(stats, key=lambda n: (-stats[n]["logical"], n)):
        s = stats[name]
        fail_pct = 100.0 * s["failed"] / s["logical"] if s["logical"] else 0.0
        hurt_pct = 100.0 * (s["failed"] + s["delayed"]) / s["logical"] if s["logical"] else 0.0
        top = max(s["blocked_by"], key=s["blocked_by"].get) if s["blocked_by"] else ""
        clients.append({"client": name, "kind": kinds.get(name, "unknown"), "logical": s["logical"],
                        "attempts": s["attempts"], "allowed": s["allowed"], "rejected": s["rejected"],
                        "failed": s["failed"], "failed_pct": round(fail_pct, 1),
                        "delayed": s["delayed"],
                        "amplification": round(s["attempts"] / s["logical"], 2) if s["logical"] else 0,
                        "max_retry_after_s": round(s["max_retry_after"], 1), "top_policy": top,
                        "first_reject_s": None if s["first_reject"] is None else round(s["first_reject"], 1)})
        k = kinds.get(name, "unknown")
        if k == "legit" and hurt_pct > 1.0:
            add("high", "RL01", "Legit client %s is throttled on %.1f%% of its requests (%d failed, %d only after "
                "retrying, waits up to %.1fs), mostly by policy '%s'; raise that limit or give this client its own tier."
                % (name, hurt_pct, s["failed"], s["delayed"], s["max_retry_after"], top))
        elif k == "legit" and s["rejected"]:
            add("low", "RL01", "Legit client %s sees %d 429s but its retries recover; check it handles Retry-After."
                % (name, s["rejected"]))
        if k == "abusive" and s["logical"]:
            share = 100.0 * s["allowed"] / s["logical"]
            if share > 25:
                add("medium", "RL02", "Abusive client %s still gets %.0f%% of its requests through (%d); "
                    "tighten the per-client limit or add a stricter policy for its pattern." % (name, share, s["allowed"]))
        amp = s["attempts"] / s["logical"] if s["logical"] else 0
        if amp >= 1.5:
            add("medium", "RL05", "Client %s sends %.2fx attempts per logical request because it retries throttled "
                "calls; retries count against the limit and add load - require Retry-After or backoff with jitter."
                % (name, amp))

    if per_sec and retry_sec.get(peak_sec, 0) > 0.5 * peak_rps and peak_rps >= 20:
        add("medium", "RL10", "Retry herd: %d of the %d requests admitted in second %d are retries released by the same "
            "Retry-After / window reset; add jitter to Retry-After (or client backoff) and prefer a token bucket or "
            "sliding window so capacity is not handed out all at once." % (retry_sec[peak_sec], peak_rps, peak_sec))
    cap = cfg.get("capacity_rps")
    if cap:
        if peak_rps > cap:
            add("high", "RL03", "Admitted traffic peaks at %d req/s (second %d) over the backend capacity of %g req/s; "
                "add or lower a global limit." % (peak_rps, peak_sec, cap))
        if not any(p["key"] == "global" for p in pols):
            per_client = [sustained_rps(p) for p in pols if p["key"] in ("client", "client+endpoint")
                          and not p["endpoints"] and not p["clients"]]
            if per_client:
                n = len(stats)
                add("medium", "RL03", "No global policy: %d clients x %g req/s per client = %g req/s possible vs capacity %g."
                    % (n, min(per_client), n * min(per_client), cap))

    policies = []
    for p, ps in zip(pols, pstats):
        obs = max((max_in_window(ts, p["window_s"]) for ts in ps["allowed_times"].values()), default=0)
        theo = theoretical_max(p)
        policies.append({"name": p["name"], "algorithm": p["algorithm"], "key": p["key"],
                         "endpoints": p["endpoints"], "clients": p["clients"], "exclude_clients": p["exclude_clients"], "checks": ps["checks"], "rejects": ps["rejects"],
                         "sustained_rps": round(sustained_rps(p), 3), "window_s": p["window_s"],
                         "worst_case_per_window": round(theo, 1), "observed_max_per_window": obs})
        if p["algorithm"] == "fixed_window" and obs > p["limit"]:
            add("medium", "RL04", "Fixed window '%s' let %d requests through in one rolling %gs window (limit %g, "
                "%.1fx) across a window boundary; use sliding_counter or a token bucket if the limit protects capacity."
                % (p["name"], obs, p["window_s"], p["limit"], obs / p["limit"]))
        if p["key"] == "global" and ps["rejects"]:
            allowed_by = defaultdict(int)
            for t, cl, _ in admitted:
                allowed_by[cl] += 1
            total = sum(allowed_by.values()) or 1
            hog = max(allowed_by, key=allowed_by.get)
            victims = [c for c in ps["by_client"] if kinds.get(c) == "legit" and c != hog]
            if allowed_by[hog] / total > 0.5 and victims:
                add("high" if kinds.get(hog) != "legit" else "medium", "RL06",
                    "Noisy neighbour: %s holds %.0f%% of admitted traffic while global policy '%s' rejects %s; "
                    "add a per-client limit below the global one." % (hog, 100.0 * allowed_by[hog] / total,
                                                                     p["name"], ", ".join(sorted(victims))))
        if p["algorithm"] == "sliding_log" and p["limit"] > 1000:
            add("low", "RL07", "Sliding log '%s' stores up to %d timestamps per key; prefer sliding_counter for large limits."
                % (p["name"], p["limit"]))
        if ps["checks"] and not ps["rejects"] and obs and theo > 10 * obs:
            add("low", "RL09", "Policy '%s' never triggered; its worst case (%g per %gs) is >10x the busiest key (%d). "
                "Fine as a safety net, but it will not stop a surge." % (p["name"], theo, p["window_s"], obs))
    if sample:
        add("info", "RL08", "Return 429 with Retry-After on every rejection (see the sample headers) and document the "
            "limits so clients can pace themselves.")
    order = {"high": 0, "medium": 1, "low": 2, "info": 3}
    findings.sort(key=lambda f: (order[f["severity"]], f["code"]))
    return {"service": cfg.get("service", "API"), "duration_s": cfg["duration_s"], "requests": len(reqs),
            "admitted": len(admitted), "peak_admitted_rps": peak_rps, "peak_second": peak_sec,
            "capacity_rps": cap, "clients": clients, "policies": policies, "findings": findings,
            "sample_429": sample}


# ----------------------------------------------------------------------------- report
def fmt(x):
    return ("%g" % x) if isinstance(x, float) else str(x)


def scope(p):
    parts = []
    if p["endpoints"]:
        parts.append(", ".join(p["endpoints"]))
    if p["clients"]:
        parts.append("only " + ", ".join(p["clients"]))
    if p["exclude_clients"]:
        parts.append("not " + ", ".join(p["exclude_clients"]))
    return "; ".join(parts) or "all"


def report(r):
    L = ["# Rate limit simulation: %s" % r["service"], ""]
    cap = (" vs capacity %g" % r["capacity_rps"]) if r["capacity_rps"] else ""
    L.append("Simulated %gs, %d logical requests, %d admitted, peak %d req/s admitted (second %d)%s."
             % (r["duration_s"], r["requests"], r["admitted"], r["peak_admitted_rps"], r["peak_second"], cap))
    highs = sum(f["severity"] == "high" for f in r["findings"])
    L += ["", "**Verdict: %s**" % ("%d high finding(s) - fix before shipping these limits" % highs if highs
                                   else "policies hold - no high findings"), ""]
    L += ["## Clients", "", "| Client | Kind | Requests | Attempts | Allowed | 429s | OK after retry | Failed | Failed % | Max Retry-After | Top policy |",
          "|---|---|---|---|---|---|---|---|---|---|---|"]
    for c in r["clients"]:
        L.append("| %s | %s | %d | %d | %d | %d | %d | %d | %.1f%% | %ss | %s |" % (
            c["client"], c["kind"], c["logical"], c["attempts"], c["allowed"], c["rejected"], c["delayed"], c["failed"],
            c["failed_pct"], fmt(c["max_retry_after_s"]), c["top_policy"] or "-"))
    L += ["", "## Policies", "", "| Policy | Algorithm | Key | Scope | Sustained | Worst case / window | Busiest key / window | Checks | Rejects |",
          "|---|---|---|---|---|---|---|---|---|"]
    for p in r["policies"]:
        L.append("| %s | %s | %s | %s | %s req/s | %s per %ss | %d | %d | %d |" % (
            p["name"], p["algorithm"], p["key"], scope(p), fmt(p["sustained_rps"]),
            fmt(p["worst_case_per_window"]), fmt(p["window_s"]), p["observed_max_per_window"], p["checks"], p["rejects"]))
    L += ["", "## Findings", ""]
    if not r["findings"]:
        L.append("- none")
    for f in r["findings"]:
        L.append("- **%s %s** %s" % (f["severity"].upper(), f["code"], f["message"]))
    s = r["sample_429"]
    if s:
        L += ["", "## Sample 429 (first rejection, t=%ss, %s %s)" % (s["t"], s["client"], s["endpoint"]), "", "```",
              "HTTP/1.1 429 Too Many Requests",
              "Retry-After: %d" % s["retry_after"],
              'RateLimit-Policy: "%s";q=%s;w=%s' % (s["policy"], fmt(float(s["quota"])), fmt(float(s["window_s"]))),
              'RateLimit: "%s";r=0;t=%d' % (s["policy"], s["retry_after"]),
              "Content-Type: application/problem+json", "```",
              "Header names follow the IETF httpapi ratelimit-headers draft; older gateways use "
              "X-RateLimit-Limit / -Remaining / -Reset instead."]
    return "\n".join(L) + "\n"


# ----------------------------------------------------------------------------- self-test
def self_test():
    cases = []

    def check(name, cond, detail=""):
        cases.append((name, bool(cond), detail))

    tb = TokenBucket(rate=1, burst=3)
    ok = 0
    for i in range(5):
        a, w, _ = tb.check("k", 0.0, 1)
        if a:
            tb.consume("k", 0.0, 1)
            ok += 1
    check("token bucket burst of 3 at t=0", ok == 3, ok)
    a, w, _ = tb.check("k", 0.0, 1)
    check("token bucket retry-after 1s", (not a) and abs(w - 1.0) < 1e-6, w)
    a, w, _ = tb.check("k", 1.0, 1)
    check("token bucket refills 1 token per second", a)

    fw = FixedWindow(limit=10, window=60)
    times = [59.0 + i * 0.01 for i in range(10)] + [60.0 + i * 0.01 for i in range(10)]
    allowed = []
    for t in times:
        a, _, _ = fw.check("k", t, 1)
        if a:
            fw.consume("k", t, 1)
            allowed.append(t)
    check("fixed window boundary burst = 2x limit", max_in_window(allowed, 60) == 20, len(allowed))
    a, w, _ = fw.check("k", 61.0, 1)
    check("fixed window retry-after until reset", (not a) and abs(w - 59.0) < 1e-6, w)

    sl = SlidingLog(limit=10, window=60)
    allowed = []
    for t in times:
        a, _, _ = sl.check("k", t, 1)
        if a:
            sl.consume("k", t, 1)
            allowed.append(t)
    check("sliding log never exceeds limit", max_in_window(allowed, 60) == 10, len(allowed))
    a, w, _ = sl.check("k", 60.5, 1)
    check("sliding log retry-after = oldest + window", (not a) and abs(w - (59.0 + 60 - 60.5)) < 1e-6, w)

    sc = SlidingCounter(limit=10, window=60)
    allowed = []
    for t in times + [90.0 + i for i in range(10)]:
        a, _, _ = sc.check("k", t, 1)
        if a:
            sc.consume("k", t, 1)
            allowed.append(t)
    first = [t for t in allowed if t < 61]
    later = [t for t in allowed if t >= 90]
    check("sliding counter blocks the boundary burst", len(first) == 10, len(first))
    check("sliding counter weights previous window (about half at mid-window)", 4 <= len(later) <= 7, len(later))

    cfg = normalize({"service": "t", "duration_s": 60, "capacity_rps": 1000, "policies": [
        {"name": "pc", "algorithm": "token_bucket", "key": "client", "rate": 5, "burst": 5}],
        "clients": [{"name": "good", "kind": "legit", "rps": 2},
                    {"name": "bad", "kind": "abusive", "rps": 20, "retry": "immediate"}]})
    r = analyse(cfg, generate(cfg))
    by = {c["client"]: c for c in r["clients"]}
    check("legit client under limit not throttled", by["good"]["rejected"] == 0, by["good"])
    check("abusive client mostly throttled", by["bad"]["allowed"] <= 5 * 60 + 10, by["bad"]["allowed"])
    check("immediate retries amplify attempts", by["bad"]["amplification"] > 1.5, by["bad"]["amplification"])
    codes = {f["code"] for f in r["findings"]}
    check("RL05 retry amplification finding", "RL05" in codes, codes)

    cfg2 = normalize({"duration_s": 30, "capacity_rps": 10, "policies": [
        {"name": "g", "algorithm": "fixed_window", "key": "global", "limit": 600, "window_s": 60}],
        "clients": [{"name": "hog", "kind": "abusive", "rps": 30},
                    {"name": "app", "kind": "legit", "rps": 1, "start": 25, "duration": 5}]})
    r2 = analyse(cfg2, generate(cfg2))
    codes2 = {f["code"]: f["severity"] for f in r2["findings"]}
    check("RL03 over capacity is high", codes2.get("RL03") == "high", codes2)
    check("RL06 noisy neighbour on global", "RL06" in codes2, codes2)
    check("RL01 legit client starved", codes2.get("RL01") == "high", codes2)

    cfg3 = normalize({"duration_s": 10, "policies": [
        {"name": "login", "algorithm": "sliding_log", "key": "client", "limit": 2, "window_s": 60, "endpoints": ["/login"]}],
        "clients": [{"name": "u", "rps": 1, "endpoint": "/orders"}, {"name": "v", "rps": 1, "endpoint": "/login"}]})
    r3 = analyse(cfg3, generate(cfg3))
    by3 = {c["client"]: c for c in r3["clients"]}
    check("endpoint-scoped policy ignores other endpoints", by3["u"]["rejected"] == 0 and by3["v"]["allowed"] == 2,
          (by3["u"], by3["v"]))
    check("burst pattern generates bursts", len(generate(normalize({"duration_s": 120, "policies": cfg3["policies"],
          "clients": [{"name": "b", "pattern": "burst", "burst": 5, "every_s": 60}]}))) == 10)
    cfg4 = normalize({"duration_s": 10, "policies": [
        {"name": "default", "algorithm": "token_bucket", "key": "client", "rate": 1, "burst": 1, "exclude_clients": ["vip"]},
        {"name": "vip", "algorithm": "token_bucket", "key": "client", "rate": 10, "burst": 10, "clients": ["vip"]}],
        "clients": [{"name": "vip", "rps": 5}, {"name": "std", "rps": 5}]})
    by4 = {c["client"]: c for c in analyse(cfg4, generate(cfg4))["clients"]}
    check("client tiers: vip unthrottled, std limited", by4["vip"]["rejected"] == 0 and by4["std"]["allowed"] <= 11,
          (by4["vip"], by4["std"]))
    try:
        normalize({"policies": [{"algorithm": "leaky"}]})
        check("bad algorithm rejected", False)
    except InputError:
        check("bad algorithm rejected", True)
    rep = report(r2)
    check("report has verdict and sample 429", "Verdict" in rep and "429 Too Many Requests" in rep)

    for name, ok, detail in cases:
        print("%s  %s%s" % ("PASS" if ok else "FAIL", name, "" if ok else "  -> %r" % (detail,)))
    passed = sum(1 for _, ok, _ in cases if ok)
    print("%d/%d passed" % (passed, len(cases)))
    return 0 if passed == len(cases) else 1


def main(argv=None):
    ap = argparse.ArgumentParser(description="Simulate API rate limit policies against traffic.")
    ap.add_argument("config", nargs="?")
    ap.add_argument("--trace", help="CSV with t,client[,endpoint][,cost] instead of generated traffic")
    ap.add_argument("--json", action="store_true")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args(argv)
    if a.self_test:
        return self_test()
    if not a.config:
        ap.print_usage(sys.stderr)
        return 2
    try:
        with open(a.config, encoding="utf-8") as f:
            cfg = normalize(json.load(f))
        reqs = read_trace(a.trace) if a.trace else generate(cfg)
        if not reqs:
            raise InputError("no traffic: add clients to the config or pass --trace")
        r = analyse(cfg, reqs)
    except (InputError, OSError, json.JSONDecodeError) as e:
        print("error: %s" % e, file=sys.stderr)
        return 2
    print(json.dumps(r, indent=2) if a.json else report(r), end="" if not a.json else "\n")
    return 1 if any(f["severity"] == "high" for f in r["findings"]) else 0


if __name__ == "__main__":
    sys.exit(main())
PerformanceRate LimitsAPI+2
F@f
0
Astro Content Site taste
Taste

Opinionated conventions for building fast, accessible and SEO-friendly content sites with Astro.

# Astro Content Site taste of a performance-minded web developer
- Use Astro for content-heavy sites like docs, blogs and marketing pages, and pick a full app framework only when most pages are interactive. Confidence: 0.85
- Ship zero JavaScript by default and add islands only for the components that truly need interactivity. Confidence: 0.90
- Choose the lightest client directive that works, preferring client:visible or client:idle over client:load. Confidence: 0.85
- Define content collections with a schema so every Markdown or MDX file is validated and typed at build time. Confidence: 0.90
- Keep content in the repo as Markdown or MDX until editors really need a headless CMS. Confidence: 0.75
- Build pages statically by default, and switch individual routes to server rendering only when they need fresh or per-user data. Confidence: 0.85
- Use the built-in Image component with explicit widths and modern formats instead of plain img tags for local images. Confidence: 0.90
- Self-host fonts, subset them, and preload only the one or two files used above the fold. Confidence: 0.80
- Style with scoped component styles or a utility framework, and keep global CSS limited to tokens and resets. Confidence: 0.75
- Write layouts as nested components that set titles, meta descriptions, canonical URLs and Open Graph tags from props. Confidence: 0.90
- Generate a sitemap and RSS feed from the content collections instead of maintaining them by hand. Confidence: 0.85
- Keep URLs stable and add redirects in config whenever a slug changes, so old links never return 404. Confidence: 0.90
- Use semantic HTML with one h1 per page, real headings in order, and alt text required by the content schema for images. Confidence: 0.90
- Use View Transitions sparingly for page navigation and respect prefers-reduced-motion. Confidence: 0.70
- Load third-party scripts like analytics and chat widgets late, or move them off the main thread with Partytown. Confidence: 0.75
- Keep framework islands in one UI library per site rather than mixing React, Vue and Svelte without a reason. Confidence: 0.80
- Run astro check and TypeScript in strict mode in CI so broken frontmatter and props fail the build. Confidence: 0.85
- Check every pull request with link checking and Lighthouse budgets for performance, accessibility and SEO. Confidence: 0.80
- Deploy previews for each pull request so writers and reviewers can read changes before they merge. Confidence: 0.85
- Add search with a static index like Pagefind before reaching for a hosted search service. Confidence: 0.75
- Read secrets only in server code through typed environment variables, and never expose them with a public prefix. Confidence: 0.95
Best PracticesPerformanceFrontend+1
F@f
0
Database Connection Pool Sizing Calculator
Skill

Sizes database connection pools for Postgres/MySQL apps from a short JSON of services, pods, workers, threads and pool settings - worst-case connections at autoscale max and during deploy surges vs max_connections, busy connections from rps x hold time, per-process wait odds (Erlang C), CPU and memory limits, PgBouncer client and server limits. Recommends pool sizes or proxy settings. Includes an offline stdlib Python calculator with --self-test.

---
name: database-connection-pool-sizing-calculator
description: Sizes database connection pools for Postgres/MySQL apps from a short JSON of services, pods, workers, threads and pool settings - worst-case connections at autoscale max and during deploy surges vs max_connections, busy connections from rps x hold time, per-process wait odds (Erlang C), CPU and memory limits, PgBouncer client and server limits. Recommends pool sizes or proxy settings. Includes an offline stdlib Python calculator with --self-test.
---

# Database Connection Pool Sizing Calculator

You work out how many database connections an application really needs and whether its pool settings can take the database down. Most "too many clients already" outages are arithmetic: pods x worker processes x (pool_size + max_overflow), multiplied again by autoscaling and rolling deploys, against a max_connections that also has to cover admin sessions, migrations and monitoring. You do that arithmetic for every service, compare it with how many connections are actually busy at peak, and return pool sizes (or proxy settings) that fit with headroom.

## Files in this skill

- `scripts/pool_sizer.py` - reads the JSON description, computes open connections today / at autoscaling maximum / during a deploy surge, busy connections (Little's law), the chance a request waits for a connection and the mean wait per process (Erlang C), CPU sweet spot and memory, PgBouncer limits, and recommends pool sizes; `--set` runs what-ifs (Python 3.8+ standard library only)
- `references/sizing-model.md` - the formulas, where each input comes from, and the limits of the model
- `references/pool-settings-by-stack.md` - what pool_size, max_overflow, threads and timeouts are called in SQLAlchemy, Django, HikariCP, node-postgres, Prisma, Rails, Go database/sql, Celery/Sidekiq, PgBouncer and RDS Proxy
- `templates/pool-sizing-review.md` - the review to hand back
- `examples/shop-pools.json` - a shop with an API (6-12 pods x 4 gthread workers, pool 10 + overflow 20), Celery workers, an admin app and a nightly report job on a 200-connection Postgres
- `examples/pool-report.md` - the real report on that file
- `examples/shop-pools-pgbouncer.json` - the fixed setup: right-sized fixed pools, API and workers through PgBouncer in transaction mode, admin and reports direct

## Workflow

### 1. Collect the inputs
For the database: engine, `max_connections`, `superuser_reserved_connections` (Postgres default 3), connections used by everything that is not an app service (admin tools, monitoring, replication, migrations, BI), vCPUs and RAM. For each service: instances now and autoscaling maximum, worker processes per instance, threads or concurrency per process (async or not), pool size and overflow, pool timeout, request timeout, and load: peak requests or jobs per second and how long one keeps a connection checked out (`conn_hold_ms`; frameworks with a session per request hold it for the whole request). If there is no hold time, use queries per request x average query time, or the pool's "checked out" gauge as `busy_connections`. Ask for the deploy strategy (maxSurge) and any proxy (PgBouncer, RDS Proxy, ProxySQL, Supavisor). Write it as JSON like `examples/shop-pools.json`.

### 2. Run the calculator
```
python3 scripts/pool_sizer.py examples/shop-pools.json
python3 scripts/pool_sizer.py pools.json --set api.max_instances=20 --set database.max_connections=400
python3 scripts/pool_sizer.py pools.json --json
python3 scripts/pool_sizer.py --self-test
```
Exit 0 = no HIGH finding, 1 = HIGH findings, 2 = the JSON is invalid (the message names the field). Without a shell, do the same sums by hand with `references/sizing-model.md`: open = instances x processes x (pool_size + max_overflow) per service; busy = rps x hold seconds; compare both with max_connections - reserved - other.

### 3. Read the result
- HIGH findings first: limits exceeded today, at autoscaling maximum or during a deploy surge, pools or proxies too small for the load, workers saturated by database time.
- Compare "busy at peak" with "open": a large gap means idle connections hold memory and slots; a transaction-mode proxy or smaller fixed pools close it.
- "Busy at peak" above the CPU sweet spot (cores x 2 + 1) means the database itself is the bottleneck: more connections make it slower, not faster. Fix hold time (short transactions, no HTTP calls inside them, indexes) or capacity.
- Treat the Erlang C numbers as a guide: they assume evenly spread, random arrivals. Check them against the pool's wait-time and checked-out metrics.

### 4. Recommend
- Prefer fixed pools (`max_overflow` 0, min idle = max) sized per process from the recommendation, never more than the threads that can use them.
- Keep at least 10% of usable connections free at max scale + deploy surge for admin sessions, failover and migrations.
- When direct connections cannot fit, put the busy services behind a transaction-mode proxy with the server pool the report suggests; keep migrations, `LISTEN/NOTIFY`, advisory locks and session settings on a direct connection.
- Raise `max_connections` only when RAM allows it, and say what it costs.
- Set pool timeouts well below the request timeout so overload fails fast instead of piling up.
- Rerun with `--set` for the next traffic peak or the next autoscaling change.

### 5. Deliver
Fill `templates/pool-sizing-review.md`: verdict, the connection budget table, findings with fixes, the new settings per service in that stack's own names, proxy settings, and what to monitor after the change.

## Example result
On `examples/shop-pools.json` the services can open 1,230 connections today, 2,430 at autoscaling maximum and 3,050 during a deploy, against 185 usable, while only about 28 are busy at peak. The API pool (10 + 20 per process) is larger than its 8 threads can ever use, and every Celery process keeps 15 connections for 1 thread. Right-sized fixed pools still need 400 direct connections, so the report suggests a transaction-mode PgBouncer with about 53 server connections. `examples/shop-pools-pgbouncer.json` applies that and fits in 80 of 185 with no HIGH finding; the remaining MEDIUM says the 8-core database is already busy at peak (28 active vs a sweet spot of 17).

## Rules

- Never guess max_connections, autoscaling limits or hold times; ask, or label the number as an assumption in the review.
- Size for the worst case the platform allows (autoscaling max + deploy surge), not today's pod count.
- Count every client of the database, including cron jobs, BI tools, migrations and replicas' replication slots.
- Do not recommend raising max_connections as the first fix; idle connections cost memory and CPU on the database.
- Give settings in the names of the user's own framework (see `references/pool-settings-by-stack.md`).
- Say clearly that the queueing numbers are a model and name the metric that confirms them.
FILE:references/sizing-model.md
# Sizing model

## Connection budget
- Usable = `max_connections - reserved - other`. Postgres keeps `superuser_reserved_connections` (default 3) for admins; managed services reserve more (RDS rdsadmin, Cloud SQL, Azure). "Other" = monitoring agents, admin tools, BI, migrations, logical replication.
- Open connections per service = `instances x processes x (pool_size + max_overflow)`.
- Autoscaling: use `max_instances`. Rolling deploy: old and new pods overlap, `ceil(max_instances x (1 + maxSurge)) x processes x pool max`.
- Via a proxy the database sees only the proxy's server connections: `min(default_pool_size x db/user pairs, max_db_connections) + reserve_pool_size`, per proxy instance.
- Headroom: keep >= 10% of usable free at max scale + surge.

## Busy connections (Little's law)
- `busy = arrival rate x time each arrival holds a connection`. 1,200 requests/s x 15 ms = 18 connections busy on average.
- Hold time is checkout to return, not query time: a framework that opens a transaction or session for the whole request holds the connection for the whole request, including template rendering and external HTTP calls.
- Without measurements: `queries per request x average query time + ~1 ms overhead`; better, read the pool's checked-out gauge at peak.
- Peaks inside a minute are higher than the per-minute average; the calculator multiplies load by `burst_factor` (default 1.3).

## Waiting for a connection (Erlang C)
- Per process, offered load `a = busy x burst / processes` (in Erlangs). With `c` connections in the pool, the probability that a checkout has to wait is Erlang C(c, a); mean wait = `C(c, a) x hold / (c - a)`.
- `a >= c` means the pool is saturated: requests queue until `pool_timeout` and then fail.
- Recommended pool = smallest `c` with C(c, a) <= target (default 1%) and utilization `a / c` <= 0.7, never more than the threads that can use connections (sync workers) and at least 2 (or the thread count if lower).
- A sync process with N threads never uses more than N connections. If `pool >= threads`, nothing waits for a connection; requests wait for a thread instead (WORKERS_SATURATED when `a` approaches `threads`).
- Assumptions: random (Poisson) arrivals, exponential hold times, load spread evenly over processes. Real traffic is burstier; use the numbers to compare options, then confirm with pool wait metrics.

## The database's own limit
- A database runs about `cores x 2 + effective spindles` queries at once efficiently (the HikariCP / PostgreSQL wiki rule of thumb; SSD -> spindles about 1). More active connections queue inside the database and add context switching and lock contention.
- So `busy at peak` above that number is a capacity or query problem, not a pool problem.
- Each Postgres backend costs roughly 5-10 MB plus `work_mem` per sort/hash node; MySQL threads about 1-3 MB plus buffers. The calculator flags open connections x MB above 25% of RAM.

## Proxies
- Transaction mode multiplexes many client connections over few server connections; session mode pins one server connection per client and saves nothing.
- Client connections to PgBouncer are cheap (~2 kB); `max_client_conn` must cover all client pools at max scale + surge, per proxy instance.
- Transaction mode loses session state between transactions: `SET`, temp tables, advisory locks, `LISTEN/NOTIFY`, `WITH HOLD` cursors; protocol-level prepared statements need PgBouncer 1.21+ (`max_prepared_statements`). Run migrations directly.
- RDS Proxy "pins" connections that use session state, which silently turns it into session mode for those clients.

## What to monitor after a change
- Pool: checked-out connections, wait time / wait count, timeouts (SQLAlchemy `QueuePool limit ... reached`, HikariCP `Connection is not available, request timed out`).
- Database: `SELECT count(*), state FROM pg_stat_activity GROUP BY state;` (`idle in transaction` = held but unused), `max_connections` usage, CPU, `wait_event` types.
- Proxy: `SHOW POOLS;` (`cl_waiting`, `maxwait`), `SHOW STATS;`.
FILE:references/pool-settings-by-stack.md
# Pool settings by stack

| Stack | Pool size | Overflow / max | Idle min | Wait timeout | Concurrency per process |
|---|---|---|---|---|---|
| SQLAlchemy (QueuePool) | `pool_size` (5) | `max_overflow` (10) | - | `pool_timeout` (30 s) | gunicorn `--threads`, uvicorn = async |
| Django | no pool before 5.1; persistent `CONN_MAX_AGE` = 1 connection per thread; 5.1+ psycopg pool `OPTIONS["pool"]` `min_size`/`max_size` | - | `min_size` | `timeout` | gunicorn workers x threads |
| HikariCP (Java/Spring) | `maximumPoolSize` (10) | - | `minimumIdle` (= max) | `connectionTimeout` (30 s) | Tomcat `server.tomcat.threads.max` (200) |
| node-postgres (pg.Pool) | `max` (10) | - | - | `connectionTimeoutMillis` (0 = forever) | async: one process, many requests |
| Prisma | `connection_limit` in the URL (cores x 2 + 1) | - | - | `pool_timeout` (10 s) | async |
| Rails ActiveRecord | `pool` in database.yml (5) | - | - | `checkout_timeout` (5 s) | Puma threads (`RAILS_MAX_THREADS`) x workers |
| Go database/sql | `SetMaxOpenConns` (0 = unlimited) | - | `SetMaxIdleConns` (2) | context deadline | goroutines: async |
| Celery | 1 connection per worker process (Django) or the SQLAlchemy pool per process | - | - | - | `--concurrency` processes, 1 task each (prefork) |
| Sidekiq | ActiveRecord `pool` >= Sidekiq `concurrency` | - | - | - | `concurrency` threads |
| PgBouncer | `default_pool_size` (20) per db/user pair, `max_db_connections` | `reserve_pool_size` | `min_pool_size` | `query_wait_timeout` (120 s) | `max_client_conn` (100) |
| RDS Proxy | `MaxConnectionsPercent` of max_connections | - | `MaxIdleConnectionsPercent` | `ConnectionBorrowTimeout` (120 s) | - |

## Mapping to the calculator's JSON
- `processes`: gunicorn/Puma workers, Celery `--concurrency` (prefork), uWSGI processes, Node cluster workers.
- `threads`: gunicorn `--threads`, Puma threads, Tomcat threads, Sidekiq concurrency. Set `async: true` for asyncio, Node, Go, reactive Java; then the pool size is the only concurrency limit.
- `pool_size` + `max_overflow`: the most connections one process can open.
- `pool_timeout_ms`, `request_timeout_ms`: the pool's wait timeout and the HTTP/load balancer timeout.
- Serverless functions (Lambda, Cloud Run with concurrency 1): each instance is one process; use the account/function concurrency limit as `max_instances` and almost always a proxy.

## Common traps
- Django `CONN_MAX_AGE` with many threads or ASGI opens one connection per thread/task and never shares them.
- Celery/RQ workers that import the web app's SQLAlchemy engine get the web pool size (e.g. 10 + 20) for a process that runs one task at a time.
- Node `pg.Pool` per request handler (a new pool on every request) instead of one per process.
- Go without `SetMaxOpenConns`: unlimited connections under load.
- Rails: Puma threads > `pool` gives `ActiveRecord::ConnectionTimeoutError`; Sidekiq needs its own pool >= concurrency.
- Health checks and readiness probes that open a new connection every few seconds per pod.
FILE:templates/pool-sizing-review.md
# Connection pool sizing review: <system>

**Database:** <engine, size, max_connections, reserved, other -> usable>   **Proxy:** <none / PgBouncer transaction mode ...>
**Verdict:** <will run out / works but wasteful / OK> - <n> HIGH, <n> MEDIUM, <n> LOW
**Inputs measured vs assumed:** <rps and hold time from APM for api; worker hold time assumed 200 ms ...>

## Connection budget
| Scenario | Open now (current settings) | With recommended settings | Usable |
|---|---|---|---|
| Today | <1,230> | <...> | <185> |
| Autoscaling max | <2,430> | <...> | <185> |
| Max + deploy surge | <3,050> | <80 via PgBouncer> | <185> |
| Busy at peak | <~28> | <~28> | CPU sweet spot <~17> |

## Findings
| Sev | What | Why it matters | Fix |
|---|---|---|---|
| <HIGH> | <pools can open 1,230 of 185> | <'too many clients' during a traffic spike or deploy> | <fixed pools + PgBouncer> |

## New settings
| Service | Setting (in its own stack) | Old | New |
|---|---|---|---|
| <api (SQLAlchemy)> | <pool_size / max_overflow / pool_timeout> | <10 / 20 / 30 s> | <5 / 0 / 2 s> |
| <celery-worker> | <pool_size / max_overflow> | <5 / 10> | <1 / 0> |

## Proxy
- <pgbouncer.ini: pool_mode = transaction, default_pool_size = 27, reserve_pool_size = 3, max_db_connections = 27, max_client_conn = 1000; 2 instances>
- <Keep direct: migrations, admin, nightly-reports (session features)>

## Database
- <max_connections stays 200; ~80 used at max + surge>
- <Busy at peak (28) above sweet spot (17): look at the slowest queries / long transactions first>

## Roll-out and monitoring
1. <deploy pool changes to workers first, then API>
2. <watch: pool wait time, timeouts, pg_stat_activity by state, PgBouncer SHOW POOLS cl_waiting/maxwait>
3. <rerun the calculator with the measured hold time after a week>

## Open questions
- <real autoscaling max for api?>
FILE:examples/shop-pools.json
{
  "database": {
    "name": "shop-orders (Postgres 16, 8 vCPU / 32 GB)",
    "engine": "postgres",
    "max_connections": 200,
    "reserved_connections": 3,
    "other_connections": 12,
    "cpu_cores": 8,
    "ram_gb": 32,
    "mb_per_connection": 10
  },
  "deploy": {"surge_percent": 25},
  "settings": {"target_wait_probability": 0.01, "burst_factor": 1.3},
  "services": [
    {
      "name": "api",
      "instances": 6,
      "max_instances": 12,
      "processes": 4,
      "threads": 8,
      "pool_size": 10,
      "max_overflow": 20,
      "peak_rps": 1200,
      "conn_hold_ms": 15,
      "pool_timeout_ms": 30000,
      "request_timeout_ms": 10000
    },
    {
      "name": "celery-worker",
      "instances": 4,
      "max_instances": 8,
      "processes": 8,
      "threads": 1,
      "pool_size": 5,
      "max_overflow": 10,
      "peak_rps": 40,
      "conn_hold_ms": 200
    },
    {
      "name": "admin",
      "instances": 2,
      "processes": 2,
      "threads": 4,
      "pool_size": 5,
      "max_overflow": 0,
      "peak_rps": 5,
      "conn_hold_ms": 30
    },
    {
      "name": "nightly-reports",
      "instances": 1,
      "processes": 1,
      "threads": 4,
      "pool_size": 5,
      "max_overflow": 5,
      "busy_connections": 2
    }
  ]
}
FILE:examples/pool-report.md
# Connection pool sizing report

Database: **shop-orders (Postgres 16, 8 vCPU / 32 GB)** (postgres), max_connections 200, reserved 3, other 12 -> **185 usable**, 8 cores (sweet spot ~17 active)
Deploy surge: 25%   Burst factor: 1.3   Target P(wait): 1.0%

**Verdict: will run out of connections or queue** - 1 HIGH, 8 MEDIUM, 3 LOW finding(s).

## Services

| Service | Path | Procs now / max | Pool (size+overflow) | Busy at peak | Per proc load | P(wait) | Mean wait | Open now | Open max | Deploy surge |
|---|---|---|---|---|---|---|---|---|---|---|
| api | direct | 24 / 48 | 10+20 | 18 (1200 rps x 15 ms) | 0.98 | 0% | 0 ms | 720 | 1440 | 1800 |
| celery-worker | direct | 32 / 64 | 5+10 | 8 (40 rps x 200 ms) | 0.33 | 0% | 0 ms | 480 | 960 | 1200 |
| admin | direct | 4 / 4 | 5+0 | 0.15 (5 rps x 30 ms) | 0.05 | 0% | 0 ms | 20 | 20 | 30 |
| nightly-reports | direct | 1 / 1 | 5+5 | 2 (given) | 2.6 | 0% | 0 ms | 10 | 10 | 20 |

## Totals against the database

| Scenario | Direct | Via proxy (server side) | Database total | Usable | Headroom |
|---|---|---|---|---|---|
| today | 1230 | 0 | 1230 | 185 | -1045 |
| autoscaling max | 2430 | 0 | 2430 | 185 | -2245 |
| max + deploy surge | 3050 | 0 | 3050 | 185 | -2865 |

Busy at peak (all services): ~28.15 connections vs ~17 the CPUs run efficiently.

## Findings

| Sev | Code | Where | What | Fix |
|---|---|---|---|---|
| HIGH | POOL_EXCEEDS_DB_LIMIT | shop-orders (Postgres 16, 8 vCPU / 32 GB) (max_connections 200 - reserved 3 - other 12 = 185 usable) | pools can open 1230 connections at today's size; the database accepts 185 - new connections fail with 'too many clients' / 'Too many connections' under load | shrink pools to the recommendation below, drop max_overflow, or put the services behind a proxy |
| MEDIUM | DB_ACTIVE_OVER_CORES | shop-orders (Postgres 16, 8 vCPU / 32 GB) | about 28.1 connections are busy at peak but 8 cores run about 17 at once efficiently (cores x 2 + spindles); the rest queue inside the database | cut connection hold time (shorter transactions, no network calls inside them), add read replicas, or scale the database |
| MEDIUM | TOO_MANY_CONNECTIONS_FOR_CORES | shop-orders (Postgres 16, 8 vCPU / 32 GB) | up to 2430 open connections for 8 cores (304 per core); idle backends cost memory, snapshot and lock-table overhead | fewer, busier connections: smaller pools or a transaction-mode proxy |
| MEDIUM | CONNECTION_MEMORY | shop-orders (Postgres 16, 8 vCPU / 32 GB) | 2430 connections x ~10 MB = 23.7 GB of 32 GB RAM before work_mem/sort buffers | reduce open connections; keep that memory for cache (shared_buffers / page cache) |
| MEDIUM | PROXY_RECOMMENDED | shop-orders (Postgres 16, 8 vCPU / 32 GB) | only ~28 connections are busy at peak but up to 2430 are open; a transaction-mode pooler multiplexes them | PgBouncer/RDS Proxy/ProxySQL in front of the database (see recommendation) |
| MEDIUM | POOL_LARGER_THAN_CONCURRENCY | api | pool max 30 per process but only 8 thread(s) can use a connection at a time; the extra 22 can never be used | pool_size <= threads; max_overflow 0 |
| MEDIUM | POOL_LARGER_THAN_CONCURRENCY | celery-worker | pool max 15 per process but only 1 thread(s) can use a connection at a time; the extra 14 can never be used | pool_size <= threads; max_overflow 0 |
| MEDIUM | POOL_LARGER_THAN_CONCURRENCY | admin | pool max 5 per process but only 4 thread(s) can use a connection at a time; the extra 1 can never be used | pool_size <= threads; max_overflow 0 |
| MEDIUM | POOL_LARGER_THAN_CONCURRENCY | nightly-reports | pool max 10 per process but only 4 thread(s) can use a connection at a time; the extra 6 can never be used | pool_size <= threads; max_overflow 0 |
| LOW | LARGE_OVERFLOW | api | max_overflow 20 >= pool_size 10 across 48 processes makes the worst case 1440 instead of 480 | fixed pools (max_overflow 0) keep the total predictable |
| LOW | POOL_TIMEOUT_LONG | api | pool_timeout 30000 ms >= request timeout 10000 ms: a request can time out while still waiting for a connection | pool_timeout around 10-30% of the request timeout so overload fails fast |
| LOW | LARGE_OVERFLOW | celery-worker | max_overflow 10 >= pool_size 5 across 64 processes makes the worst case 960 instead of 320 | fixed pools (max_overflow 0) keep the total predictable |

## Recommended pools

| Service | pool_size | max_overflow | P(wait) per proc | Open at max | With deploy surge |
|---|---|---|---|---|---|
| api | 5 | 0 | 0.3% | 240 | 300 |
| celery-worker | 1 | 0 | 0% | 64 | 80 |
| admin | 2 | 0 | 0.1% | 8 | 12 |
| nightly-reports | 4 | 0 | 0% | 4 | 8 |

Database connections needed with these pools at max scale + deploy surge: **400** (direct 400 + proxy 0) of 185 usable -> still does NOT fit.

Direct connections cannot fit. Put the services behind a transaction-mode proxy: about **53** server connections (default_pool_size / max_db_connections) cover peak x burst with P(wait) under 1.0%; keep client pools as above and set max_client_conn above the client total.
Or raise max_connections to at least 457 (check RAM: ~10 MB per connection).

Model: Little's law for busy connections, Erlang C (M/M/c) per process with load spread evenly; peak load x burst factor. Validate with the pool's checked-out and wait metrics.
FILE:examples/shop-pools-pgbouncer.json
{
  "database": {
    "name": "shop-orders (Postgres 16, 8 vCPU / 32 GB)",
    "engine": "postgres",
    "max_connections": 200,
    "reserved_connections": 3,
    "other_connections": 12,
    "cpu_cores": 8,
    "ram_gb": 32,
    "mb_per_connection": 10
  },
  "proxy": {
    "type": "pgbouncer",
    "pool_mode": "transaction",
    "instances": 2,
    "default_pool_size": 27,
    "max_db_connections": 27,
    "reserve_pool_size": 3,
    "max_client_conn": 1000
  },
  "deploy": {"surge_percent": 25},
  "settings": {"target_wait_probability": 0.01, "burst_factor": 1.3},
  "services": [
    {
      "name": "api",
      "via_proxy": true,
      "instances": 6,
      "max_instances": 12,
      "processes": 4,
      "threads": 8,
      "pool_size": 5,
      "max_overflow": 0,
      "peak_rps": 1200,
      "conn_hold_ms": 15,
      "pool_timeout_ms": 2000,
      "request_timeout_ms": 10000
    },
    {
      "name": "celery-worker",
      "via_proxy": true,
      "instances": 4,
      "max_instances": 8,
      "processes": 8,
      "threads": 1,
      "pool_size": 1,
      "max_overflow": 0,
      "peak_rps": 40,
      "conn_hold_ms": 200
    },
    {
      "name": "admin",
      "instances": 2,
      "processes": 2,
      "threads": 4,
      "pool_size": 2,
      "max_overflow": 0,
      "peak_rps": 5,
      "conn_hold_ms": 30
    },
    {
      "name": "nightly-reports",
      "instances": 1,
      "processes": 1,
      "threads": 4,
      "pool_size": 4,
      "max_overflow": 0,
      "busy_connections": 2
    }
  ]
}
FILE:scripts/pool_sizer.py
#!/usr/bin/env python3
"""Database connection pool sizing calculator (Python 3.8+ standard library only).

Reads a JSON description of a database, an optional PgBouncer-style proxy and the services
that connect to it, then answers:
  - worst-case open connections at normal size, at autoscaling maximum and during a rolling
    deploy surge, against what the database really allows (max_connections - reserved - other)
  - how many connections are actually busy at peak (Little's law: rate x hold time)
  - per process: chance a request waits for a free connection and the mean wait (Erlang C),
    and the smallest pool that keeps waiting under the target
  - database side: busy connections against the CPU sweet spot (cores x 2 + 1), memory used by
    open connections, proxy client/server limits and pool-mode caveats
  - a recommended pool_size / max_overflow per service and, when direct connections cannot fit,
    proxy settings that do

Input (JSON):
  {"database": {"name": "orders-db", "engine": "postgres", "max_connections": 200,
                "reserved_connections": 3, "other_connections": 12, "cpu_cores": 8,
                "ram_gb": 32, "mb_per_connection": 10},
   "proxy": {"type": "pgbouncer", "pool_mode": "transaction", "default_pool_size": 30,
             "max_db_connections": 60, "max_client_conn": 2000, "instances": 1},      (optional)
   "deploy": {"surge_percent": 25},
   "settings": {"target_wait_probability": 0.01, "burst_factor": 1.3},                (optional)
   "services": [{"name": "api", "instances": 6, "max_instances": 12, "processes": 4,
                 "threads": 8, "pool_size": 10, "max_overflow": 20, "peak_rps": 1200,
                 "conn_hold_ms": 15, "pool_timeout_ms": 30000, "request_timeout_ms": 10000,
                 "via_proxy": false, "async": false}]}
  conn_hold_ms = how long one request/job keeps a connection checked out (session-per-request
  frameworks hold it for the whole request); or give queries_per_request + avg_query_ms.
  For jobs without a rate, give busy_connections (average connections in use).

Usage:
  python3 pool_sizer.py pools.json [--set api.max_instances=16] [--json]
  python3 pool_sizer.py --self-test

Exit codes: 0 = no HIGH finding, 1 = HIGH findings (limits exceeded, pools that queue),
2 = bad input.
"""
import argparse
import copy
import json
import math
import sys

SEV_ORDER = {"HIGH": 0, "MEDIUM": 1, "LOW": 2}
DEFAULTS = {"target_wait_probability": 0.01, "burst_factor": 1.3, "max_utilization": 0.7}
ENGINE_MB = {"postgres": 10, "postgresql": 10, "mysql": 3, "mariadb": 3}


class InputError(ValueError):
    pass


def erlang_c(c, a):
    """Probability that an arrival waits (all c servers busy), offered load a Erlangs."""
    if c <= 0:
        return 1.0
    if a <= 0:
        return 0.0
    if a >= c:
        return 1.0
    b = 1.0
    for k in range(1, c + 1):
        b = a * b / (k + a * b)
    return c * b / (c - a * (1 - b))


def mean_wait_ms(c, a, hold_ms):
    """Mean wait for a connection in ms (M/M/c)."""
    if a <= 0:
        return 0.0
    if a >= c:
        return float("inf")
    return erlang_c(c, a) * hold_ms / (c - a)


def smallest_pool(a, target, max_util, cap=None, floor=1):
    c = max(floor, 1)
    while True:
        if erlang_c(c, a) <= target and a / c <= max_util:
            return c if cap is None else min(c, cap)
        if cap is not None and c >= cap:
            return cap
        c += 1
        if c > 10000:
            return c


def num(d, key, default=None, kind=float, minimum=0, where=""):
    v = d.get(key, default)
    if v is None:
        return None
    if isinstance(v, bool) or not isinstance(v, (int, float)):
        raise InputError("%s%s must be a number, got %r" % (where, key, v))
    if v < minimum:
        raise InputError("%s%s must be >= %s, got %r" % (where, key, minimum, v))
    return kind(v)


def apply_set(cfg, expr):
    """--set api.max_instances=16 | database.max_connections=300 | proxy.default_pool_size=40"""
    if "=" not in expr or "." not in expr.split("=")[0]:
        raise InputError("--set needs <service|database|proxy|deploy|settings>.<key>=<value>, got %r" % expr)
    path, val = expr.split("=", 1)
    target, key = path.split(".", 1)
    try:
        value = json.loads(val)
    except ValueError:
        value = val
    if target in ("database", "proxy", "deploy", "settings"):
        cfg.setdefault(target, {})[key] = value
        return
    for s in cfg.get("services", []):
        if s.get("name") == target:
            s[key] = value
            return
    raise InputError("--set: no service named %r" % target)


class Plan:
    def __init__(self, cfg):
        self.cfg = cfg
        self.findings = []
        self.settings = dict(DEFAULTS)
        self.settings.update(cfg.get("settings") or {})
        self._db()
        self._proxy()
        self.surge = num(cfg.get("deploy") or {}, "surge_percent", 25, where="deploy.") / 100.0
        self.services = [self._service(s, i) for i, s in enumerate(cfg.get("services") or [])]
        if not self.services:
            raise InputError("no services given")
        names = [s["name"] for s in self.services]
        if len(set(names)) != len(names):
            raise InputError("service names must be unique")
        self._totals()
        self._check()

    def add(self, code, sev, where, what, fix):
        self.findings.append({"code": code, "sev": sev, "where": where, "what": what, "fix": fix})

    def _db(self):
        d = self.cfg.get("database")
        if not isinstance(d, dict):
            raise InputError("missing 'database' object")
        engine = str(d.get("engine", "postgres")).lower()
        self.db = {
            "name": d.get("name", "database"),
            "engine": engine,
            "max_connections": num(d, "max_connections", 100 if engine.startswith("postgres") else 151, int, 1, "database."),
            "reserved": num(d, "reserved_connections", 3 if engine.startswith("postgres") else 0, int, 0, "database."),
            "other": num(d, "other_connections", 0, int, 0, "database."),
            "cores": num(d, "cpu_cores", None, float, 0.5, "database."),
            "ram_gb": num(d, "ram_gb", None, float, 0.1, "database."),
            "mb_per_conn": num(d, "mb_per_connection", ENGINE_MB.get(engine, 10), float, 0, "database."),
            "spindles": num(d, "effective_spindles", 1, float, 0, "database."),
        }
        self.db["available"] = self.db["max_connections"] - self.db["reserved"] - self.db["other"]
        if self.db["available"] <= 0:
            raise InputError("database: reserved + other connections leave nothing for the services")

    def _proxy(self):
        p = self.cfg.get("proxy")
        if not p:
            self.proxy = None
            return
        mode = str(p.get("pool_mode", "transaction")).lower()
        if mode not in ("session", "transaction", "statement"):
            raise InputError("proxy.pool_mode must be session, transaction or statement")
        inst = num(p, "instances", 1, int, 1, "proxy.")
        pool = num(p, "default_pool_size", 20, int, 1, "proxy.")
        pairs = num(p, "db_user_pairs", 1, int, 1, "proxy.")
        maxdb = num(p, "max_db_connections", 0, int, 0, "proxy.")
        per_inst = pool * pairs if not maxdb else min(pool * pairs, maxdb)
        self.proxy = {"type": p.get("type", "pgbouncer"), "mode": mode, "instances": inst,
                      "default_pool_size": pool, "pairs": pairs, "max_db_connections": maxdb,
                      "reserve_pool_size": num(p, "reserve_pool_size", 0, int, 0, "proxy."),
                      "max_client_conn": num(p, "max_client_conn", 100, int, 1, "proxy."),
                      "server_conns": (per_inst + num(p, "reserve_pool_size", 0, int, 0, "proxy.")) * inst}

    def _service(self, s, i):
        w = "services[%d]." % i
        name = s.get("name") or "service%d" % (i + 1)
        r = {"name": name, "via_proxy": bool(s.get("via_proxy", False)), "async": bool(s.get("async", False))}
        r["instances"] = num(s, "instances", 1, int, 0, w)
        r["max_instances"] = max(num(s, "max_instances", r["instances"], int, 0, w), r["instances"])
        r["processes"] = num(s, "processes", 1, int, 1, w)
        r["threads"] = num(s, "threads", None, int, 1, w)
        r["pool_size"] = num(s, "pool_size", 5, int, 0, w)
        r["max_overflow"] = num(s, "max_overflow", 0, int, 0, w)
        r["pool_max"] = r["pool_size"] + r["max_overflow"]
        if r["pool_max"] < 1:
            raise InputError("%s: pool_size + max_overflow must be at least 1" % name)
        r["pool_timeout_ms"] = num(s, "pool_timeout_ms", 30000, float, 0, w)
        r["request_timeout_ms"] = num(s, "request_timeout_ms", None, float, 1, w)
        hold = num(s, "conn_hold_ms", None, float, 0, w)
        if hold is None and s.get("queries_per_request") is not None:
            hold = num(s, "queries_per_request", 0, float, 0, w) * num(s, "avg_query_ms", 0, float, 0, w) \
                + num(s, "overhead_ms", 1, float, 0, w)
        r["hold_ms"] = hold
        r["rps"] = num(s, "peak_rps", None, float, 0, w)
        r["busy_given"] = num(s, "busy_connections", None, float, 0, w)
        procs_now = r["instances"] * r["processes"]
        procs_max = r["max_instances"] * r["processes"]
        r["procs_now"], r["procs_max"] = procs_now, procs_max
        r["procs_surge"] = int(math.ceil(r["max_instances"] * (1 + self.surge))) * r["processes"] if r["max_instances"] else 0
        r["open_steady"] = procs_now * r["pool_size"]
        r["open_now"] = procs_now * r["pool_max"]
        r["open_max"] = procs_max * r["pool_max"]
        r["open_surge"] = r["procs_surge"] * r["pool_max"]
        burst = float(self.settings["burst_factor"])
        if r["rps"] is not None and r["hold_ms"] is not None:
            r["busy"] = r["rps"] * r["hold_ms"] / 1000.0
            r["load_source"] = "%g rps x %g ms" % (r["rps"], r["hold_ms"])
        elif r["busy_given"] is not None:
            r["busy"] = r["busy_given"]
            r["load_source"] = "given"
        else:
            r["busy"] = None
            r["load_source"] = "unknown"
        if r["busy"] is not None and procs_now:
            r["a_proc"] = r["busy"] * burst / procs_now  # offered load per process at peak x burst
            cap = r["threads"] if (r["threads"] and not r["async"]) else None
            hold_ms = r["hold_ms"] if r["hold_ms"] else 100.0
            # a sync process never runs more than `threads` queries at once: with pool >= threads
            # no request ever waits for a connection (it waits for a thread instead)
            r["p_wait"] = self.conn_wait(r["pool_max"], r["a_proc"], cap)
            r["wait_ms"] = 0.0 if (cap and r["pool_max"] >= cap) else mean_wait_ms(r["pool_max"], r["a_proc"], hold_ms)
            floor = min(2, cap) if cap else 2
            rec = smallest_pool(r["a_proc"], float(self.settings["target_wait_probability"]),
                                float(self.settings["max_utilization"]), cap, floor)
            r["rec_pool"] = rec
            r["rec_p_wait"] = self.conn_wait(rec, r["a_proc"], cap)
        else:
            r["a_proc"] = r["p_wait"] = r["wait_ms"] = r["rec_pool"] = r["rec_p_wait"] = None
        return r

    @staticmethod
    def conn_wait(pool, a, cap):
        if cap and pool >= cap:
            return 0.0
        return erlang_c(pool, a)

    def _totals(self):
        direct = [s for s in self.services if not s["via_proxy"]]
        proxied = [s for s in self.services if s["via_proxy"]]
        t = {}
        for k in ("open_steady", "open_now", "open_max", "open_surge"):
            t["direct_" + k] = sum(s[k] for s in direct)
            t["proxied_" + k] = sum(s[k] for s in proxied)
        server = self.proxy["server_conns"] if (self.proxy and proxied) else 0
        t["proxy_server"] = server
        for k in ("open_now", "open_max", "open_surge"):
            t["db_" + k] = t["direct_" + k] + server
        t["busy"] = sum(s["busy"] or 0 for s in self.services)
        t["busy_proxied"] = sum(s["busy"] or 0 for s in proxied)
        t["unknown_load"] = [s["name"] for s in self.services if s["busy"] is None]
        if self.db["cores"]:
            t["sweet_spot"] = int(round(self.db["cores"] * 2 + self.db["spindles"]))
        else:
            t["sweet_spot"] = None
        self.t = t

    def _check(self):
        db, t = self.db, self.t
        avail = db["available"]
        label = "%s (max_connections %d - reserved %d - other %d = %d usable)" % (
            db["name"], db["max_connections"], db["reserved"], db["other"], avail)
        if t["db_open_now"] > avail:
            self.add("POOL_EXCEEDS_DB_LIMIT", "HIGH", label,
                     "pools can open %d connections at today's size; the database accepts %d - new connections "
                     "fail with 'too many clients' / 'Too many connections' under load" % (t["db_open_now"], avail),
                     "shrink pools to the recommendation below, drop max_overflow, or put the services behind a proxy")
        elif t["db_open_max"] > avail:
            self.add("AUTOSCALE_EXCEEDS_DB_LIMIT", "HIGH", label,
                     "fine today (%d) but %d at autoscaling maximum - the scale-out that should save a traffic "
                     "spike is what exhausts the database" % (t["db_open_now"], t["db_open_max"]),
                     "size pools for max_instances, cap max_instances, or use a proxy")
        elif t["db_open_surge"] > avail:
            self.add("DEPLOY_SURGE_EXCEEDS_LIMIT", "HIGH", label,
                     "a rolling deploy at maximum scale runs %d%% extra pods for a while: %d connections > %d"
                     % (round(self.surge * 100), t["db_open_surge"], avail),
                     "lower maxSurge, deploy at lower scale, or leave this much headroom")
        elif t["db_open_surge"] > 0.9 * avail:
            self.add("LOW_CONNECTION_HEADROOM", "MEDIUM", label,
                     "deploy surge at max scale reaches %d of %d usable (%.0f%%)" % (
                         t["db_open_surge"], avail, 100.0 * t["db_open_surge"] / avail),
                     "keep at least 10% free for admin sessions, migrations and failover")
        if t["sweet_spot"] and t["busy"] > t["sweet_spot"]:
            sev = "HIGH" if t["busy"] > 2 * t["sweet_spot"] else "MEDIUM"
            self.add("DB_ACTIVE_OVER_CORES", sev, db["name"],
                     "about %.1f connections are busy at peak but %g cores run about %d at once efficiently "
                     "(cores x 2 + spindles); the rest queue inside the database" % (t["busy"], db["cores"], t["sweet_spot"]),
                     "cut connection hold time (shorter transactions, no network calls inside them), add read "
                     "replicas, or scale the database")
        open_max = t["db_open_max"]
        if t["sweet_spot"] and open_max > max(5 * t["sweet_spot"], 100):
            self.add("TOO_MANY_CONNECTIONS_FOR_CORES", "MEDIUM", db["name"],
                     "up to %d open connections for %g cores (%.0f per core); idle backends cost memory, "
                     "snapshot and lock-table overhead" % (open_max, db["cores"], open_max / db["cores"]),
                     "fewer, busier connections: smaller pools or a transaction-mode proxy")
        if db["ram_gb"] and db["mb_per_conn"]:
            mem = open_max * db["mb_per_conn"] / 1024.0
            if mem > 0.25 * db["ram_gb"]:
                self.add("CONNECTION_MEMORY", "MEDIUM", db["name"],
                         "%d connections x ~%g MB = %.1f GB of %g GB RAM before work_mem/sort buffers"
                         % (open_max, db["mb_per_conn"], mem, db["ram_gb"]),
                         "reduce open connections; keep that memory for cache (shared_buffers / page cache)")
        if self.proxy:
            self._check_proxy()
        elif t["db_open_max"] > avail and t["busy"] and t["busy"] * 3 < avail:
            self.add("PROXY_RECOMMENDED", "MEDIUM", db["name"],
                     "only ~%.0f connections are busy at peak but up to %d are open; a transaction-mode "
                     "pooler multiplexes them" % (t["busy"], t["db_open_max"]),
                     "PgBouncer/RDS Proxy/ProxySQL in front of the database (see recommendation)")
        for s in self.services:
            self._check_service(s)

    def _check_proxy(self):
        p, t = self.proxy, self.t
        proxied = [s for s in self.services if s["via_proxy"]]
        if not proxied:
            self.add("PROXY_UNUSED", "LOW", p["type"], "a proxy is configured but no service has via_proxy true",
                     "set via_proxy on the services that use it")
            return
        per_inst_clients = int(math.ceil(t["proxied_open_surge"] / float(p["instances"])))
        if per_inst_clients > p["max_client_conn"]:
            self.add("PROXY_CLIENT_LIMIT", "HIGH", p["type"],
                     "proxied pools can open %d client connections per proxy instance (deploy surge, max scale) "
                     "but max_client_conn is %d" % (per_inst_clients, p["max_client_conn"]),
                     "raise max_client_conn (cheap: ~2 kB each) or shrink the client pools")
        if p["mode"] == "session" and t["proxied_open_max"] > p["server_conns"]:
            self.add("PROXY_SESSION_MODE", "MEDIUM", p["type"],
                     "session mode pins one server connection per client connection, so %d client connections "
                     "cannot share %d server connections" % (t["proxied_open_max"], p["server_conns"]),
                     "use transaction mode (check the caveats) or size like direct connections")
        if p["mode"] in ("transaction", "statement"):
            self.add("PROXY_TRANSACTION_MODE_CAVEATS", "LOW", p["type"],
                     "%s mode: session state does not survive between transactions (SET, temp tables, advisory "
                     "locks, LISTEN/NOTIFY, WITH HOLD cursors; prepared statements need PgBouncer 1.21+ "
                     "max_prepared_statements)" % p["mode"],
                     "run migrations and session-level jobs on a direct connection")
        busy = t["busy_proxied"] * float(self.settings["burst_factor"])
        hold = [s["hold_ms"] for s in proxied if s["hold_ms"]]
        if busy:
            pw = erlang_c(p["server_conns"], busy)
            if busy >= p["server_conns"] or pw > 0.2:
                self.add("PROXY_POOL_TOO_SMALL", "HIGH", p["type"],
                         "~%.1f server connections busy at peak x burst but only %d exist (P(wait) %.0f%%)"
                         % (busy, p["server_conns"], 100 * pw),
                         "raise default_pool_size/max_db_connections to %d" % smallest_pool(
                             busy, float(self.settings["target_wait_probability"]), float(self.settings["max_utilization"])))
            elif pw > float(self.settings["target_wait_probability"]) * 5:
                self.add("PROXY_POOL_TIGHT", "MEDIUM", p["type"],
                         "P(wait) for a server connection at peak x burst is %.1f%%" % (100 * pw),
                         "add a reserve_pool_size of a few connections or raise default_pool_size")
        if hold and max(hold) > 1000 and p["mode"] != "session":
            self.add("LONG_HOLD_THROUGH_PROXY", "LOW", p["type"],
                     "a proxied service holds connections for %g ms; long transactions block multiplexing" % max(hold),
                     "move long reports/batches to their own pool or a replica")

    def _check_service(self, s):
        n = s["name"]
        if s["busy"] is None:
            self.add("MISSING_LOAD_DATA", "LOW", n, "no peak_rps + conn_hold_ms (or busy_connections): pool size "
                     "cannot be checked against load", "measure: pool checked-out gauge or rps x average hold time")
            return
        if s["procs_now"] and s["a_proc"] >= s["pool_max"]:
            self.add("POOL_TOO_SMALL", "HIGH", n,
                     "each process needs ~%.2f connections at peak x burst but its pool max is %d: requests queue "
                     "until pool_timeout (%g ms)" % (s["a_proc"], s["pool_max"], s["pool_timeout_ms"]),
                     "pool %d per process (or more processes)" % s["rec_pool"])
        elif s["p_wait"] is not None and s["p_wait"] > 0.2:
            self.add("POOL_TOO_SMALL", "HIGH", n, "P(wait for a connection) %.0f%% at peak x burst, mean wait %.1f ms"
                     % (100 * s["p_wait"], s["wait_ms"]), "pool %d per process" % s["rec_pool"])
        elif s["p_wait"] is not None and s["p_wait"] > max(0.05, float(self.settings["target_wait_probability"])):
            self.add("POOL_TIGHT", "MEDIUM", n, "P(wait for a connection) %.1f%% at peak x burst" % (100 * s["p_wait"]),
                     "pool %d per process" % s["rec_pool"])
        if s["threads"] and not s["async"] and s["a_proc"] > 0.7 * s["threads"]:
            self.add("WORKERS_SATURATED", "HIGH" if s["a_proc"] >= s["threads"] else "MEDIUM", n,
                     "each process spends ~%.2f of its %d thread(s) inside the database at peak x burst; requests "
                     "queue for a thread, and a bigger pool cannot help" % (s["a_proc"], s["threads"]),
                     "shorter connection hold time, or more processes/threads (then re-check the database totals)")
        if s["threads"] and not s["async"] and s["pool_max"] > s["threads"]:
            self.add("POOL_LARGER_THAN_CONCURRENCY", "MEDIUM", n,
                     "pool max %d per process but only %d thread(s) can use a connection at a time; the extra "
                     "%d can never be used" % (s["pool_max"], s["threads"], s["pool_max"] - s["threads"]),
                     "pool_size <= threads; max_overflow 0")
        elif s["rec_pool"] and s["pool_max"] > max(2 * s["rec_pool"], s["rec_pool"] + 5):
            self.add("POOL_OVERSIZED", "LOW", n, "pool max %d per process where %d keeps P(wait) under %.0f%%"
                     % (s["pool_max"], s["rec_pool"], 100 * float(self.settings["target_wait_probability"])),
                     "pool %d per process frees %d connections at max scale"
                     % (s["rec_pool"], (s["pool_max"] - s["rec_pool"]) * s["procs_max"]))
        if s["max_overflow"] and s["max_overflow"] >= s["pool_size"] and s["procs_max"] > 4:
            self.add("LARGE_OVERFLOW", "LOW", n, "max_overflow %d >= pool_size %d across %d processes makes the "
                     "worst case %d instead of %d" % (s["max_overflow"], s["pool_size"], s["procs_max"],
                                                       s["open_max"], s["procs_max"] * s["pool_size"]),
                     "fixed pools (max_overflow 0) keep the total predictable")
        if s["request_timeout_ms"] and s["pool_timeout_ms"] >= s["request_timeout_ms"]:
            self.add("POOL_TIMEOUT_LONG", "LOW", n, "pool_timeout %g ms >= request timeout %g ms: a request can time "
                     "out while still waiting for a connection" % (s["pool_timeout_ms"], s["request_timeout_ms"]),
                     "pool_timeout around 10-30% of the request timeout so overload fails fast")

    def recommendation(self):
        rec = []
        tot_max = tot_surge = 0
        for s in self.services:
            p = s["rec_pool"] if s["rec_pool"] is not None else s["pool_max"]
            o_max = s["procs_max"] * p
            o_surge = s["procs_surge"] * p
            rec.append({"name": s["name"], "pool_size": p, "max_overflow": 0, "per_process_p_wait": s["rec_p_wait"],
                        "open_max": o_max, "open_surge": o_surge, "via_proxy": s["via_proxy"]})
            if not s["via_proxy"]:
                tot_max += o_max
                tot_surge += o_surge
        server = self.t["proxy_server"]
        need = tot_surge + server
        out = {"services": rec, "direct_open_surge": tot_surge, "proxy_server": server, "db_needed": need,
               "fits": need <= self.db["available"]}
        busy = self.t["busy"] * float(self.settings["burst_factor"])
        if busy:
            out["proxy_pool_if_all_proxied"] = smallest_pool(busy, float(self.settings["target_wait_probability"]),
                                                             float(self.settings["max_utilization"]))
        out["max_connections_needed"] = int(math.ceil((need + self.db["reserved"] + self.db["other"]) * 1.1))
        return out

    def worst(self):
        return min((f["sev"] for f in self.findings), key=lambda x: SEV_ORDER[x]) if self.findings else None


def f1(x):
    if x is None:
        return "-"
    if x == float("inf"):
        return "inf"
    return ("%.2f" % x).rstrip("0").rstrip(".") if abs(x) < 100 else "%.0f" % x


def pct(x):
    if x is None:
        return "-"
    return "%.1f%%" % (100 * x) if x >= 0.001 else ("<0.1%" if x > 0 else "0%")


def render(pl):
    db, t, p = pl.db, pl.t, pl.proxy
    w = pl.worst()
    o = ["# Connection pool sizing report", ""]
    o.append("Database: **%s** (%s), max_connections %d, reserved %d, other %d -> **%d usable**%s" % (
        db["name"], db["engine"], db["max_connections"], db["reserved"], db["other"], db["available"],
        (", %g cores (sweet spot ~%d active)" % (db["cores"], t["sweet_spot"])) if db["cores"] else ""))
    if p:
        o.append("Proxy: %s, %s mode, %d instance(s), %d server connections to the database, max_client_conn %d"
                 % (p["type"], p["mode"], p["instances"], p["server_conns"], p["max_client_conn"]))
    o.append("Deploy surge: %d%%   Burst factor: %g   Target P(wait): %s" % (
        round(pl.surge * 100), float(pl.settings["burst_factor"]), pct(float(pl.settings["target_wait_probability"]))))
    o.append("")
    if not w:
        o.append("**Verdict: OK** - pools fit the database at max scale and deploy surge, and requests rarely wait.")
    else:
        n = {s: sum(1 for f in pl.findings if f["sev"] == s) for s in SEV_ORDER}
        o.append("**Verdict: %s** - %d HIGH, %d MEDIUM, %d LOW finding(s)." % (
            {"HIGH": "will run out of connections or queue", "MEDIUM": "works, but wasteful or tight",
             "LOW": "fine, minor tuning"}[w], n["HIGH"], n["MEDIUM"], n["LOW"]))
    o += ["", "## Services", "",
          "| Service | Path | Procs now / max | Pool (size+overflow) | Busy at peak | Per proc load | P(wait) | Mean wait | Open now | Open max | Deploy surge |",
          "|---|---|---|---|---|---|---|---|---|---|---|"]
    for s in pl.services:
        o.append("| %s | %s | %d / %d | %d+%d | %s (%s) | %s | %s | %s | %d | %d | %d |" % (
            s["name"], "proxy" if s["via_proxy"] else "direct", s["procs_now"], s["procs_max"], s["pool_size"],
            s["max_overflow"], f1(s["busy"]), s["load_source"], f1(s["a_proc"]), pct(s["p_wait"]),
            ("%s ms" % f1(s["wait_ms"])) if s["wait_ms"] is not None else "-", s["open_now"], s["open_max"], s["open_surge"]))
    o += ["", "## Totals against the database", "", "| Scenario | Direct | Via proxy (server side) | Database total | Usable | Headroom |", "|---|---|---|---|---|---|"]
    for k, lab in (("open_now", "today"), ("open_max", "autoscaling max"), ("open_surge", "max + deploy surge")):
        tot = t["db_" + k]
        o.append("| %s | %d | %d | %d | %d | %d |" % (lab, t["direct_" + k], t["proxy_server"], tot,
                                                       db["available"], db["available"] - tot))
    o.append("")
    o.append("Busy at peak (all services): ~%s connections%s." % (
        f1(t["busy"]), (" vs ~%d the CPUs run efficiently" % t["sweet_spot"]) if t["sweet_spot"] else ""))
    if t["unknown_load"]:
        o.append("No load data for: %s." % ", ".join(t["unknown_load"]))
    if pl.findings:
        o += ["", "## Findings", "", "| Sev | Code | Where | What | Fix |", "|---|---|---|---|---|"]
        for f in sorted(pl.findings, key=lambda f: SEV_ORDER[f["sev"]]):
            o.append("| %s | %s | %s | %s | %s |" % (f["sev"], f["code"], f["where"], f["what"].replace("|", "/"), f["fix"]))
    r = pl.recommendation()
    o += ["", "## Recommended pools", "", "| Service | pool_size | max_overflow | P(wait) per proc | Open at max | With deploy surge |", "|---|---|---|---|---|---|"]
    for s in r["services"]:
        o.append("| %s | %d | 0 | %s | %d | %d%s |" % (s["name"], s["pool_size"], pct(s["per_process_p_wait"]),
                                                       s["open_max"], s["open_surge"], " (client side, via proxy)" if s["via_proxy"] else ""))
    o.append("")
    o.append("Database connections needed with these pools at max scale + deploy surge: **%d** (direct %d + proxy %d) "
             "of %d usable -> %s." % (r["db_needed"], r["direct_open_surge"], r["proxy_server"], db["available"],
                                      "fits" if r["fits"] else "still does NOT fit"))
    if not r["fits"]:
        if r.get("proxy_pool_if_all_proxied"):
            o.append("")
            o.append("Direct connections cannot fit. Put the services behind a transaction-mode proxy: about "
                     "**%d** server connections (default_pool_size / max_db_connections) cover peak x burst with "
                     "P(wait) under %s; keep client pools as above and set max_client_conn above the client total."
                     % (r["proxy_pool_if_all_proxied"], pct(float(pl.settings["target_wait_probability"]))))
        o.append("Or raise max_connections to at least %d (check RAM: ~%g MB per connection)." % (
            r["max_connections_needed"], db["mb_per_conn"]))
    o += ["", "Model: Little's law for busy connections, Erlang C (M/M/c) per process with load spread evenly; "
          "peak load x burst factor. Validate with the pool's checked-out and wait metrics."]
    return "\n".join(o) + "\n"


def as_json(pl):
    def clean(x):
        if isinstance(x, float) and (math.isinf(x) or math.isnan(x)):
            return None
        if isinstance(x, dict):
            return {k: clean(v) for k, v in x.items()}
        if isinstance(x, list):
            return [clean(v) for v in x]
        return x
    return clean({"database": pl.db, "proxy": pl.proxy, "totals": pl.t, "services": pl.services,
                  "findings": pl.findings, "worst": pl.worst(), "recommendation": pl.recommendation()})


def self_test():
    cases = []

    def case(name, fn):
        try:
            ok, err = bool(fn()), ""
        except Exception as e:  # noqa
            ok, err = False, repr(e)
        cases.append((name, ok, err))

    def cfg(**kw):
        c = {"database": {"name": "db", "max_connections": 100, "reserved_connections": 3, "other_connections": 7,
                          "cpu_cores": 4, "ram_gb": 16},
             "deploy": {"surge_percent": 25},
             "services": [{"name": "api", "instances": 2, "max_instances": 4, "processes": 2, "threads": 4,
                           "pool_size": 4, "max_overflow": 0, "peak_rps": 200, "conn_hold_ms": 10}]}
        for k, v in kw.items():
            if k == "svc":
                c["services"][0].update(v)
            elif k == "services":
                c["services"] = v
            else:
                c.setdefault(k, {}).update(v)
        return c

    def codes(c):
        return {f["code"]: f["sev"] for f in Plan(c).findings}

    def raises(fn):
        try:
            fn()
        except InputError:
            return True
        return False

    case("erlang C one server equals load", lambda: abs(erlang_c(1, 0.5) - 0.5) < 1e-9)
    case("erlang C textbook value (c=2, a=1 -> 1/3)", lambda: abs(erlang_c(2, 1.0) - 1 / 3.0) < 1e-9)
    case("erlang C saturated -> 1", lambda: erlang_c(3, 3.0) == 1.0 and erlang_c(3, 5) == 1.0)
    case("erlang C decreases with servers", lambda: erlang_c(5, 3) > erlang_c(6, 3) > erlang_c(8, 3))
    case("mean wait M/M/1", lambda: abs(mean_wait_ms(1, 0.5, 10) - 10.0) < 1e-9)
    case("smallest pool meets target", lambda: (lambda c: erlang_c(c, 2.0) <= 0.01 and erlang_c(c - 1, 2.0) > 0.01 or 2.0 / (c - 1) > 0.7)(smallest_pool(2.0, 0.01, 0.7)))
    case("smallest pool capped by threads", lambda: smallest_pool(9.0, 0.01, 0.7, cap=4) == 4)
    case("usable connections", lambda: Plan(cfg()).db["available"] == 90)
    case("open totals", lambda: (lambda p: (p.t["db_open_now"], p.t["db_open_max"], p.t["db_open_surge"]) == (16, 32, 40))(Plan(cfg())))
    case("busy via Little's law", lambda: abs(Plan(cfg()).services[0]["busy"] - 2.0) < 1e-9)
    case("queries x avg ms as hold", lambda: abs(Plan(cfg(svc={"conn_hold_ms": None, "queries_per_request": 4, "avg_query_ms": 2, "overhead_ms": 2})).services[0]["hold_ms"] - 10) < 1e-9)
    case("healthy config has no HIGH", lambda: Plan(cfg()).worst() in (None, "LOW", "MEDIUM"))
    case("exceeds limit today", lambda: codes(cfg(svc={"pool_size": 30}))["POOL_EXCEEDS_DB_LIMIT"] == "HIGH")
    case("autoscale exceeds", lambda: "AUTOSCALE_EXCEEDS_DB_LIMIT" in codes(cfg(svc={"max_instances": 12})))
    case("deploy surge exceeds", lambda: "DEPLOY_SURGE_EXCEEDS_LIMIT" in codes(cfg(svc={"max_instances": 11, "pool_size": 4}, deploy={"surge_percent": 50})))
    case("pool too small", lambda: codes(cfg(svc={"pool_size": 1, "peak_rps": 400}))["POOL_TOO_SMALL"] == "HIGH")
    case("pool larger than threads", lambda: "POOL_LARGER_THAN_CONCURRENCY" in codes(cfg(svc={"pool_size": 10, "threads": 2})))
    case("pool >= threads never waits for a connection", lambda: Plan(cfg(svc={"pool_size": 1, "threads": 1, "peak_rps": 20})).services[0]["p_wait"] == 0.0)
    case("workers saturated", lambda: codes(cfg(svc={"threads": 1, "pool_size": 1, "peak_rps": 400}))["WORKERS_SATURATED"] == "HIGH")
    case("async services not capped by threads", lambda: "POOL_LARGER_THAN_CONCURRENCY" not in codes(cfg(svc={"pool_size": 10, "threads": 1, "async": True})))
    case("large overflow flagged", lambda: "LARGE_OVERFLOW" in codes(cfg(svc={"pool_size": 2, "max_overflow": 2, "threads": 8})))
    case("pool timeout longer than request", lambda: "POOL_TIMEOUT_LONG" in codes(cfg(svc={"pool_timeout_ms": 30000, "request_timeout_ms": 10000})))
    case("db over cores", lambda: "DB_ACTIVE_OVER_CORES" in codes(cfg(svc={"peak_rps": 1500, "pool_size": 4, "threads": 8, "max_instances": 2}, database={"max_connections": 500})))
    case("connection memory", lambda: "CONNECTION_MEMORY" in codes(cfg(database={"ram_gb": 0.5})))
    case("missing load data", lambda: "MISSING_LOAD_DATA" in codes(cfg(svc={"peak_rps": None})))
    case("busy_connections accepted", lambda: Plan(cfg(svc={"peak_rps": None, "busy_connections": 1.5})).services[0]["busy"] == 1.5)
    case("proxy server conns counted, not clients", lambda: (lambda p: p.t["db_open_max"] == 20)(Plan(cfg(svc={"via_proxy": True}, proxy={"pool_mode": "transaction", "default_pool_size": 20, "max_client_conn": 1000}))))
    case("max_db_connections caps proxy", lambda: Plan(cfg(svc={"via_proxy": True}, proxy={"default_pool_size": 50, "max_db_connections": 30})).proxy["server_conns"] == 30)
    case("proxy client limit", lambda: "PROXY_CLIENT_LIMIT" in codes(cfg(svc={"via_proxy": True, "max_instances": 40}, proxy={"max_client_conn": 100})))
    case("proxy pool too small", lambda: "PROXY_POOL_TOO_SMALL" in codes(cfg(svc={"via_proxy": True, "peak_rps": 1000}, proxy={"default_pool_size": 5, "max_client_conn": 1000})))
    case("session mode warning", lambda: "PROXY_SESSION_MODE" in codes(cfg(svc={"via_proxy": True, "max_instances": 10}, proxy={"pool_mode": "session", "default_pool_size": 10, "max_client_conn": 1000})))
    case("proxy recommended when direct cannot fit", lambda: "PROXY_RECOMMENDED" in codes(cfg(svc={"max_instances": 30, "pool_size": 4})))
    case("--set overrides service", lambda: (lambda c: (apply_set(c, "api.max_instances=9"), c["services"][0]["max_instances"] == 9)[1])(cfg()))
    case("--set overrides database", lambda: (lambda c: (apply_set(c, "database.max_connections=300"), Plan(c).db["max_connections"] == 300)[1])(cfg()))
    case("--set unknown service rejected", lambda: raises(lambda: apply_set(cfg(), "nope.pool_size=3")))
    case("bad number rejected", lambda: raises(lambda: Plan(cfg(svc={"pool_size": "ten"}))))
    case("no services rejected", lambda: raises(lambda: Plan(cfg(services=[]))))
    case("duplicate names rejected", lambda: raises(lambda: Plan(cfg(services=[{"name": "a"}, {"name": "a"}]))))
    case("reserved too large rejected", lambda: raises(lambda: Plan(cfg(database={"reserved_connections": 100}))))
    case("recommendation fits for sane config", lambda: Plan(cfg()).recommendation()["fits"])
    case("render has tables", lambda: "## Recommended pools" in render(Plan(cfg())) and "## Totals against the database" in render(Plan(cfg())))
    case("json output serializable", lambda: json.dumps(as_json(Plan(cfg(svc={"pool_size": 1, "peak_rps": 900})))) is not None)

    passed = sum(1 for _, ok, _ in cases if ok)
    for name, ok, err in cases:
        print(("PASS " if ok else "FAIL ") + name + ((" " + err) if err else ""))
    print("%d/%d passed" % (passed, len(cases)))
    return 0 if passed == len(cases) else 1


def main(argv=None):
    ap = argparse.ArgumentParser(description="Size database connection pools against load and database limits.")
    ap.add_argument("file", nargs="?", help="JSON description ('-' = stdin)")
    ap.add_argument("--set", action="append", default=[], metavar="TARGET.KEY=VALUE",
                    help="what-if override, e.g. api.max_instances=16 or database.max_connections=400 (repeatable)")
    ap.add_argument("--json", action="store_true")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args(argv)
    if a.self_test:
        return self_test()
    if not a.file:
        ap.error("give a JSON file or --self-test")
    try:
        text = sys.stdin.read() if a.file == "-" else open(a.file, encoding="utf-8").read()
        cfg = json.loads(text)
        cfg = copy.deepcopy(cfg)
        for e in a.set:
            apply_set(cfg, e)
        pl = Plan(cfg)
    except (OSError, ValueError) as e:
        print("error: %s" % e, file=sys.stderr)
        return 2
    sys.stdout.write(json.dumps(as_json(pl), indent=2) + "\n" if a.json else render(pl))
    return 1 if pl.worst() == "HIGH" else 0


if __name__ == "__main__":
    sys.exit(main())
PerformanceDatabaseBackend+2
F@f
0
Full-Text Search taste
Taste

Opinionated conventions for building relevant, fast and maintainable full-text search into applications.

# Full-Text Search taste of a search-focused backend engineer
- Start with the database's built-in full-text search, such as PostgreSQL tsvector, and add a dedicated search engine only when relevance or scale really needs it. Confidence: 0.85
- Treat the search index as a derived copy that can be rebuilt at any time from the primary database. Confidence: 0.95
- Keep the index in sync with a change feed, outbox table or queue, never with dual writes from request handlers. Confidence: 0.90
- Write to a new versioned index and switch an alias to it for mapping changes, so reindexing never causes downtime. Confidence: 0.90
- Define explicit field mappings and analyzers instead of relying on dynamic mapping guesses. Confidence: 0.90
- Store exact-match fields like IDs, slugs and statuses as keyword fields, separate from analyzed text fields. Confidence: 0.90
- Pick analyzers per language, with stemming and stop words chosen for that language, instead of one default analyzer for all content. Confidence: 0.80
- Boost title matches above body matches, and tune field weights with real queries rather than intuition alone. Confidence: 0.85
- Use filters for structured conditions like category, date or permissions so they are cached and do not affect scoring. Confidence: 0.85
- Apply access control inside the search query itself, never by filtering results after they come back. Confidence: 0.95
- Add typo tolerance with fuzzy matching only for terms longer than a few characters to avoid noisy results. Confidence: 0.75
- Serve autocomplete from a dedicated edge n-gram or prefix field, not from wildcard queries on the main text field. Confidence: 0.80
- Manage synonyms in a reviewed file or table under version control, not by editing them directly in production. Confidence: 0.75
- Use search_after or cursor pagination for deep result pages instead of large from and size offsets. Confidence: 0.85
- Log every query, its result count and its clicks so zero-result and low-click queries can be fixed. Confidence: 0.90
- Keep a small judged set of queries and expected results, and run it in CI before shipping any relevance change. Confidence: 0.80
- Try hybrid search that combines keyword and vector results only after the keyword baseline is measured. Confidence: 0.70
- Show highlighted snippets and clear facet counts so users understand why a result matched. Confidence: 0.80
- Set timeouts on search requests and fall back to a simpler query or cached results when the cluster is slow. Confidence: 0.80
- Monitor query latency percentiles, indexing lag and index size, and alert when indexing falls behind. Confidence: 0.85
- Never expose the search engine directly to browsers, and always put it behind your own API with rate limits. Confidence: 0.95
Best PracticesPerformanceDatabase+1
F@f
0
Realtime WebSocket taste
Taste

Opinionated conventions for building secure, scalable realtime features with WebSockets.

# Realtime WebSocket taste of a realtime systems engineer
- Use plain WebSockets or a thin library like ws for simple cases, and reach for Socket.IO only when you need its fallbacks and rooms. Confidence: 0.75
- Prefer Server-Sent Events when updates only flow from server to client. Confidence: 0.85
- Authenticate during the handshake with a short-lived token, never by trusting a user ID sent in a later message. Confidence: 0.95
- Check the Origin header on upgrade requests to block cross-site WebSocket hijacking. Confidence: 0.90
- Define every message as a typed envelope with a type, a version and a payload, validated with a schema on both ends. Confidence: 0.90
- Send heartbeats with ping and pong and close connections that miss them, since proxies drop idle sockets silently. Confidence: 0.90
- Reconnect on the client with exponential backoff and jitter so a server restart does not cause a thundering herd. Confidence: 0.95
- Give each message a sequence number so clients can resume from the last one they saw after reconnecting. Confidence: 0.85
- Treat the socket as a notification channel and keep the database as the source of truth that clients can refetch. Confidence: 0.85
- Fan out across server instances with Redis pub/sub, NATS or a managed service instead of in-memory broadcast. Confidence: 0.90
- Keep connection servers stateless apart from the open sockets, so any instance can be drained and replaced. Confidence: 0.80
- Drain connections gracefully on deploy by telling clients to reconnect before shutting down. Confidence: 0.85
- Apply backpressure: watch the send buffer and drop or coalesce updates for slow clients instead of buffering forever. Confidence: 0.85
- Rate limit incoming messages per connection and cap message size. Confidence: 0.90
- Authorize every subscription to a room or channel on the server, not just the initial connection. Confidence: 0.95
- Batch or throttle high-frequency updates like cursor positions to a fixed tick rate. Confidence: 0.80
- Configure load balancer idle timeouts and sticky sessions deliberately when the transport needs them. Confidence: 0.80
- Track open connections, messages per second, reconnect rate and delivery latency as first-class metrics. Confidence: 0.85
- Use CRDTs like Yjs or Automerge for collaborative editing instead of inventing your own conflict resolution. Confidence: 0.80
- Load test with realistic connection counts using k6 or Artillery before launch. Confidence: 0.80
Best PracticesPerformanceArchitecture+2
F@f
0
SQL Query Performance Reviewer
Skill

Reviews SQL queries and optional EXPLAIN output for common performance problems such as SELECT *, functions or casts on indexed columns, leading-wildcard LIKE, N+1 query loops, OR across columns vs UNION ALL, AND/OR precedence slips, NOT IN subqueries, deep OFFSET paging, seq scans and disk sorts. Explains each problem and gives a rewritten query. Includes a stdlib Python checker with --self-test.

---
name: sql-query-performance-reviewer
description: Reviews SQL queries and optional EXPLAIN output for common performance problems such as SELECT *, functions or casts on indexed columns, leading-wildcard LIKE, N+1 query loops, OR across columns vs UNION ALL, AND/OR precedence slips, NOT IN subqueries, deep OFFSET paging, seq scans and disk sorts. Explains each problem and gives a rewritten query. Includes a stdlib Python checker with --self-test.
---

# SQL Query Performance Reviewer

You review SQL the way an experienced database engineer does in a code review: you read the query and its plan, find the patterns that make it slow (or quietly wrong), and hand back a rewritten query with a short reason for every change. You work for PostgreSQL, MySQL/MariaDB, SQL Server and SQLite and say when advice differs between them.

## Files in this skill

- `scripts/sql_review.py` - scans a .sql file (one or many statements) and optional EXPLAIN output, prints findings by severity (Python 3 standard library only; never connects to a database or runs the SQL)
- `references/anti-patterns.md` - each finding with why it hurts, a before/after rewrite and engine differences
- `references/reading-explain.md` - how to capture and read EXPLAIN in PostgreSQL and MySQL, and which numbers matter
- `templates/review-report.md` - the review you hand back: summary, findings table, rewritten queries, what to measure
- `examples/order-history.sql`, `examples/order-history-explain.txt`, `examples/indexes.txt` - an online shop's order history page with 7 statements, a PostgreSQL plan and the known indexes

## Workflow

### 1. Collect the inputs
Ask for: the query or a log excerpt with the real statements, the database engine and version, rough table sizes, and if possible `EXPLAIN (ANALYZE, BUFFERS)` (PostgreSQL) or `EXPLAIN ANALYZE` / `EXPLAIN ... \G` (MySQL 8) output. Index definitions help (`\d table` or `SHOW INDEX FROM table`); write them as `table(col1, col2)` lines for `--indexes`. Ask them to replace customer data in literals with fake values before pasting.

### 2. Run the checker
```
python3 scripts/sql_review.py examples/order-history.sql --explain examples/order-history-explain.txt --indexes examples/indexes.txt
python3 scripts/sql_review.py slow.sql --json
python3 scripts/sql_review.py --self-test
```
Exit code 1 means HIGH findings, 2 means bad input. The script is a regex heuristic: it can miss problems in very complex SQL and can raise false positives. Read every statement yourself as well.

### 3. Review
Order the work: correctness first (AND_OR_PRECEDENCE, NOT_IN_SUBQUERY, NO_WHERE_WRITE), then the biggest cost from the plan (SEQ_SCAN_LARGE, ROWS_REMOVED, DISK_SORT), then N_PLUS_ONE (often the largest total time in an app), then the rest. For each finding give the rewrite from `references/anti-patterns.md` adapted to the user's columns. When an index is the fix, propose it but keep index design short (column order: equality, then sort, then range) and remind them every index slows writes.

### 4. Deliver
Fill `templates/review-report.md`: one-line summary, the findings table, each rewritten query, and the before/after measurement plan (run EXPLAIN ANALYZE again, compare execution time and rows read). Never claim a speed-up you did not measure; say "expected".

## Example result
For the example files: 7 statements, 6 HIGH, 7 MEDIUM, 2 LOW. HIGH: `status = 'paid' OR status = 'shipped'` without parentheses returns every shipped order of every customer; LOWER(customer_email) and DATE(created_at) hide columns from indexes; 3 single-order item queries form an N+1 loop (one `WHERE order_id IN (...)` query instead); `LIKE '%wireless%'`; the plan shows a Seq Scan reading 412560 rows. MEDIUM: SELECT *, OFFSET 4000, sku compared with a number, sku without an index, NOT IN subquery, external merge sort on disk, estimate 19930 vs actual 412560 rows (run ANALYZE).

## Rules

- Never run SQL against the user's database yourself and never ask for production credentials.
- Ask for anonymized literals; do not repeat personal data from pasted queries in the report.
- Correctness beats speed: point out queries that return wrong rows even if they are fast.
- Prefer rewriting the query over adding an index; add an index only for a query that runs often or is slow.
- Name the engine when advice is engine-specific (e.g. expression indexes, ILIKE, LIMIT a,b).
- Measured plans beat heuristics: if EXPLAIN ANALYZE disagrees with a finding, trust the plan.
FILE:references/anti-patterns.md
# SQL Performance Anti-Patterns

Each section: what the checker flags, why it hurts, and a rewrite. "Sargable" means the database can use an index to find the rows (Search ARGument ABLE).

## AND_OR_PRECEDENCE (HIGH, correctness)
AND binds tighter than OR, so `customer_id = 7 AND status = 'paid' OR status = 'shipped'` means `(customer_id = 7 AND status = 'paid') OR status = 'shipped'`: every shipped order of every customer, and a full scan.
```
-- after
WHERE customer_id = 7 AND status IN ('paid', 'shipped')
```

## FUNC_ON_COLUMN (HIGH)
`WHERE LOWER(email) = ?`, `YEAR(created_at) = 2026`, `DATE(created_at) = ?`, `price * 2 > 100`: the index stores raw values, so the function must run on every row.
```
-- dates: use a half-open range on the raw column
WHERE created_at >= '2026-10-01' AND created_at < '2026-10-02'
-- arithmetic: move it to the constant side
WHERE price > 50
-- case-insensitive search: store normalized data or index the expression
CREATE INDEX ON customers (LOWER(email));          -- PostgreSQL, SQLite 3.9+
ALTER TABLE customers ADD email_lc VARCHAR(255) AS (LOWER(email)) STORED, ADD INDEX (email_lc);  -- MySQL 5.7+
-- MySQL 8.0.13+ also supports functional indexes: CREATE INDEX ix ON customers ((LOWER(email)));
-- PostgreSQL alternative: the citext type
```

## LEADING_WILDCARD (HIGH)
`LIKE '%wireless%'` cannot use a B-tree index (only a prefix like `'wireless%'` can). Options: full-text search (PostgreSQL `tsvector` + GIN, MySQL `FULLTEXT` + `MATCH ... AGAINST`), a trigram index (`CREATE EXTENSION pg_trgm; CREATE INDEX ... USING gin (name gin_trgm_ops)`), a search engine for product search, or a reversed column for suffix searches (`'%@example.com'`).

## N_PLUS_ONE (HIGH)
One query for a list, then one query per row (an ORM lazy-loading a relation). 50 orders = 51 round trips; each is fast, the page is slow.
```
-- before (x N)
SELECT product_id, qty FROM order_items WHERE order_id = 98211;
-- after (1 query)
SELECT order_id, product_id, qty FROM order_items WHERE order_id IN (98211, 98340, 98502);
-- or join it into the list query
```
ORM fixes: Django `prefetch_related`/`select_related`, Rails `includes`, SQLAlchemy `selectinload`, Hibernate `JOIN FETCH` / `@BatchSize`, Prisma `include`. The checker needs the repeated statements in the file (paste a log excerpt).

## ORDER_BY_RANDOM (HIGH)
`ORDER BY RAND() LIMIT 1` reads and sorts the whole table. Pick a random id in range and take the next row (`WHERE id >= ? ORDER BY id LIMIT 1`), keep a random-number column with an index, or use `TABLESAMPLE SYSTEM (1)` in PostgreSQL.

## NO_WHERE_WRITE (HIGH)
`UPDATE`/`DELETE` without WHERE locks and rewrites every row. If that is intended, do it in batches (`DELETE ... WHERE id IN (SELECT id ... LIMIT 5000)` in a loop) or use `TRUNCATE`.

## SELECT_STAR (MEDIUM)
Reads every column (including large text/JSON), sends more bytes, prevents index-only scans and breaks callers when columns change. List the columns. `SELECT *` inside `EXISTS (...)` is fine.

## OR_ACROSS_COLUMNS (MEDIUM) and OR_SAME_COLUMN (LOW)
`WHERE email = ? OR phone = ?`: one index cannot serve both. PostgreSQL may combine two indexes with a BitmapOr and MySQL with index_merge; if the plan shows a scan instead, split:
```
SELECT id FROM users WHERE email = ?
UNION ALL
SELECT id FROM users WHERE phone = ? AND email IS DISTINCT FROM ?;  -- avoid duplicates (MySQL: NOT (email <=> ?))
```
Same column repeated: `status IN ('paid', 'shipped')` is shorter and plans the same or better.

## IMPLICIT_CAST (MEDIUM) and QUOTED_NUMBER (LOW)
A text column compared with a number (`sku = 40017` on a VARCHAR): MySQL converts every row's value to a number, so the index is skipped and '040017' also matches; PostgreSQL raises an operator error. Quote the value. A numeric column compared with a quoted number (`customer_id = '1042'`) is converted once and is usually fine, but it often means the application binds ids as strings; a parameter typed as text can force a cast on the column side in some drivers (JDBC `setString` on SQL Server NVARCHAR vs VARCHAR is the classic case).

## NOT_IN_SUBQUERY (MEDIUM, correctness)
If the subquery returns a single NULL, `NOT IN` returns no rows at all. Use:
```
SELECT c.id FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
```
NOT EXISTS plans as an anti-join in every major engine.

## DEEP_OFFSET (MEDIUM)
`LIMIT 20 OFFSET 4000` reads 4020 rows and throws away 4000; page 500 is 25x slower than page 1. Keyset (seek) pagination:
```
SELECT id, created_at, total FROM orders
WHERE customer_id = ? AND (created_at, id) < (?, ?)      -- last row of the previous page
ORDER BY created_at DESC, id DESC
LIMIT 20;
```
Index `(customer_id, created_at, id)`. MySQL supports row comparisons too; SQL Server: `created_at < ? OR (created_at = ? AND id < ?)`.

## COUNT_FOR_EXISTS (LOW)
`SELECT COUNT(*) ... > 0` counts all matches. `SELECT EXISTS (SELECT 1 FROM ... WHERE ...)` stops at the first.

## DISTINCT_JOIN (LOW)
`SELECT DISTINCT u.* FROM users u JOIN orders o ...` builds all user x order rows then removes duplicates. Use `WHERE EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id)`.

## NO_INDEX_FOR_FILTER (MEDIUM, needs --indexes)
A column used in WHERE/ON is not the first column of any listed index. Not every filter needs an index (small tables, low-selectivity flags, rare queries). Composite index order: equality columns first, then the ORDER BY column, then range columns; include selected columns for an index-only scan only when the query is hot.
FILE:references/reading-explain.md
# Reading EXPLAIN

## Capture
| Engine | Command | Notes |
|---|---|---|
| PostgreSQL | `EXPLAIN (ANALYZE, BUFFERS) <query>;` | ANALYZE runs the query; wrap writes in `BEGIN; ... ROLLBACK;` |
| MySQL 8 | `EXPLAIN ANALYZE <query>;` or `EXPLAIN <query>\G` | The checker parses the `\G` vertical format |
| MariaDB | `ANALYZE <query>;` / `EXPLAIN <query>\G` | |
| SQL Server | `SET STATISTICS IO, TIME ON;` + actual execution plan | Read manually |
| SQLite | `EXPLAIN QUERY PLAN <query>;` | Look for `SCAN table` vs `SEARCH table USING INDEX` |

Run it on production-like data. A plan on a 1000-row dev table tells you nothing about a 50-million-row table.

## What the checker looks for
| Finding | PostgreSQL sign | MySQL sign |
|---|---|---|
| SEQ_SCAN_LARGE | `Seq Scan on t` with actual rows >= 10000 | `type: ALL`, `rows` >= 10000, `key: NULL` |
| ROWS_REMOVED | `Rows Removed by Filter` >= 9x the rows kept | `filtered` <= 10% on >= 1000 rows |
| EST_MISMATCH | `rows=` estimate vs `actual ... rows=` off by 10x | (EXPLAIN ANALYZE only, read manually) |
| DISK_SORT | `Sort Method: external merge  Disk: ...` | `Using temporary; Using filesort` |
| NESTED_LOOP_MANY | inner node with `loops=` >= 1000 | many rows in the driving table + `ref` lookups |

## Reading a PostgreSQL plan
- Read from the most indented node up; each `->` feeds its parent.
- `cost=a..b` is the planner's guess (arbitrary units), `actual time=a..b` is milliseconds per loop; multiply by `loops`.
- `rows=` in the cost part is the estimate, in the actual part the real count. A 10x miss means stale or missing statistics: `ANALYZE table;`, or extended statistics for correlated columns (`CREATE STATISTICS`).
- `Index Scan` / `Index Only Scan` / `Bitmap Index Scan` = index used. `Heap Fetches` high on an index-only scan = run VACUUM.
- `Buffers: shared read=` counts 8 kB pages from disk; `hit=` from cache.
- `Sort Method: external merge` = the sort did not fit in `work_mem`. Prefer an index that returns rows in order; raise work_mem per session only for known reporting queries.

## Reading MySQL EXPLAIN
- `type` from best to worst: `const`, `eq_ref`, `ref`, `range`, `index` (full index scan), `ALL` (full table scan).
- `key` is the index chosen (`NULL` = none); `possible_keys` lists candidates.
- `rows` x `filtered`% = rows passed on to the next step.
- `Extra`: `Using index` (covering, good), `Using where` (filter after reading), `Using temporary` and `Using filesort` (extra work for GROUP BY / ORDER BY).

## Before/after measurement
1. Run the original 3 times, record median execution time and rows/buffers read.
2. Apply one change at a time (rewrite, then index).
3. Run again with the same parameters; also test a "big" customer and a "small" one, because plans change with data skew.
4. Check write cost for new indexes on hot tables (insert latency, index size with `pg_relation_size` or `information_schema.STATISTICS`).
FILE:templates/review-report.md
# SQL performance review: <query or endpoint name>

**Engine:** <PostgreSQL 16 / MySQL 8.0 / ...>   **Tables:** <orders ~1.2M rows, order_items ~4M>
**Summary:** <one sentence: the main problem and the expected effect of the fix>

## Findings
| # | Severity | Finding | Statement | Why it matters | Fix |
|---|---|---|---|---|---|
| 1 | HIGH | <AND_OR_PRECEDENCE> | <stmt 1> | <returns all shipped orders, full scan> | <parenthesize / IN (...)> |
| 2 | <MEDIUM> | <...> | <...> | <...> | <...> |

## Rewritten queries
### Statement <n>: <name>
Before:
```sql
<original>
```
After:
```sql
<rewrite>
```
Why: <one or two sentences>

## Index changes (only if needed)
```sql
<CREATE INDEX CONCURRENTLY ix_orders_customer_created ON orders (customer_id, created_at DESC, id);>
```
Write cost: <table write rate, expected index size>

## Measure
| Query | Before (ms, rows read) | After (ms, rows read) |
|---|---|---|
| <stmt 1> | <912 ms, 1.2M rows> | <expected: < 5 ms, ~20 rows> |

Run `EXPLAIN (ANALYZE, BUFFERS)` again after each change, with a large and a small customer.

## Not changed
<findings deliberately left, e.g. SELECT * in an admin export, with the reason>
FILE:examples/order-history.sql
-- Order history page of a small online shop (PostgreSQL), captured from the app log.
-- 1. Order list for the account page
SELECT * FROM orders o
WHERE LOWER(o.customer_email) = 'mina.sato@example.com'
  AND o.status = 'paid' OR o.status = 'shipped'
ORDER BY o.created_at DESC
LIMIT 20 OFFSET 4000;

-- 2-4. Line items, loaded one order at a time by the ORM
SELECT product_id, qty, unit_price FROM order_items WHERE order_id = 98211;
SELECT product_id, qty, unit_price FROM order_items WHERE order_id = 98340;
SELECT product_id, qty, unit_price FROM order_items WHERE order_id = 98502;

-- 5. Search box
SELECT p.id, p.name FROM products p
WHERE p.name LIKE '%wireless%' AND p.sku = 40017;

-- 6. Customers who never ordered
SELECT c.id, c.email FROM customers c
WHERE c.id NOT IN (SELECT customer_id FROM orders)
  AND DATE(c.created_at) = '2026-10-01';

-- 7. Order lookup by id from a URL parameter
SELECT o.id, o.total FROM orders o WHERE o.customer_id = '1042';
FILE:examples/order-history-explain.txt
Limit  (cost=48211.30..48211.35 rows=20 width=212) (actual time=912.4..912.5 rows=20 loops=1)
  ->  Sort  (cost=48201.30..48251.12 rows=19930 width=212) (actual time=905.1..911.8 rows=4020 loops=1)
        Sort Key: created_at DESC
        Sort Method: external merge  Disk: 18432kB
        ->  Seq Scan on orders o  (cost=0.00..41870.00 rows=19930 width=212) (actual time=0.03..801.7 rows=412560 loops=1)
              Filter: (((lower(customer_email) = 'mina.sato@example.com'::text) AND (status = 'paid'::text)) OR (status = 'shipped'::text))
              Rows Removed by Filter: 787440
Planning Time: 0.4 ms
Execution Time: 914.9 ms
FILE:examples/indexes.txt
orders(customer_id, created_at)
orders(status)
order_items(order_id)
customers(id)
products(id)
FILE:scripts/sql_review.py
#!/usr/bin/env python3
"""SQL query performance reviewer (Python 3 standard library only).

Reads a .sql file (one or more statements separated by ;) and, optionally, EXPLAIN output,
and flags common performance problems with a heuristic, regex-based scan. It does not connect
to a database and never runs the SQL. Treat findings as review prompts, not proof.

Query findings (severity):
  HIGH   FUNC_ON_COLUMN     function or arithmetic wraps a column in WHERE/ON (index cannot be used)
  HIGH   LEADING_WILDCARD   LIKE/ILIKE pattern starts with % or _ (full scan)
  HIGH   N_PLUS_ONE         the same statement shape repeats >= --repeat times with different literals
  HIGH   ORDER_BY_RANDOM    ORDER BY RAND()/RANDOM() sorts the whole table
  HIGH   NO_WHERE_WRITE     UPDATE or DELETE without WHERE
  HIGH   AND_OR_PRECEDENCE  AND and OR mixed without parentheses: AND binds first, so the OR branch
                            matches rows from the whole table (wrong results and a full scan)
  MEDIUM SELECT_STAR        SELECT * or alias.* (wide rows, no covering index, breaks on schema change)
  MEDIUM OR_ACROSS_COLUMNS  OR between different columns in WHERE (consider UNION ALL)
  MEDIUM IMPLICIT_CAST      code/phone/sku-like (text) column compared with a bare number: MySQL
                            casts every row and skips the index, PostgreSQL raises a type error
  MEDIUM NOT_IN_SUBQUERY    NOT IN (SELECT ...): NULL trap and poor anti-join plans; use NOT EXISTS
  MEDIUM DEEP_OFFSET        OFFSET (or LIMIT a,b) >= 1000: keyset pagination instead
  MEDIUM NO_INDEX_FOR_FILTER  (needs --indexes) filtered/joined column not leading any known index
  LOW    QUOTED_NUMBER      id/number column compared with a quoted number: usually fine for a literal,
                            but a sign the app binds ids as text (typed text parameters can force a cast)
  LOW    OR_SAME_COLUMN     col = a OR col = b: write col IN (a, b)
  LOW    COUNT_FOR_EXISTS   COUNT(*) > 0 used as an existence check; use EXISTS
  LOW    DISTINCT_JOIN      SELECT DISTINCT with JOIN may hide a join fan-out
EXPLAIN findings (PostgreSQL text format and MySQL EXPLAIN \\G vertical format):
  HIGH   SEQ_SCAN_LARGE     Seq Scan / type ALL over >= --large-rows rows
  MEDIUM ROWS_REMOVED       a filter throws away >= 90% of the rows it reads
  MEDIUM EST_MISMATCH       estimated vs actual rows differ by >= 10x (stale statistics)
  MEDIUM DISK_SORT          external merge sort / Using filesort with Using temporary
  LOW    NESTED_LOOP_MANY   inner side of a nested loop runs >= 1000 loops
Usage:
  python3 sql_review.py query.sql
  python3 sql_review.py query.sql --explain plan.txt --indexes indexes.txt --json
  python3 sql_review.py --self-test
--indexes file: one index per line, e.g. "orders(customer_id, created_at)".
Exit code: 0 no HIGH findings, 1 HIGH findings, 2 bad input.
"""
import argparse
import json
import re
import sys
from collections import defaultdict

SEV_ORDER = {"HIGH": 0, "MEDIUM": 1, "LOW": 2}
FUNCS = ("lower", "upper", "trim", "ltrim", "rtrim", "date", "year", "month", "day", "cast",
         "coalesce", "ifnull", "nvl", "substring", "substr", "left", "right", "to_char",
         "date_trunc", "extract", "date_format", "convert", "abs", "round", "concat", "length")
ID_COL = re.compile(r"(^|_)(id|number|count|qty|quantity|amount)$")
TEXT_COL = re.compile(r"(phone|zip|postal_code|postcode|sku|isbn|iban|code|_no)$")
KEYWORDS = {"where", "on", "and", "or", "not", "join", "left", "right", "inner", "outer", "full",
            "cross", "group", "order", "by", "limit", "offset", "having", "union", "select", "from",
            "as", "using", "set", "values", "into", "lateral", "natural", "straight_join", "with"}


class DataError(ValueError):
    pass


def mask(sql):
    """Remove comments, replace string literals with 'Sn' tokens; return (masked, literals)."""
    sql = re.sub(r"--[^\n]*", " ", sql)
    sql = re.sub(r"/\*.*?\*/", " ", sql, flags=re.S)
    lits = []

    def rep(m):
        lits.append(m.group(0)[1:-1].replace("''", "'"))
        return f"'S{len(lits) - 1}'"
    return re.sub(r"'(?:[^']|'')*'", rep, sql), lits


def split_statements(text):
    masked, lits = mask(text)
    out = []
    for part in masked.split(";"):
        s = " ".join(part.split())
        if s:
            out.append(s)
    return out, lits


def clause(stmt, start, enders):
    m = re.search(r"\b" + start + r"\b", stmt, re.I)
    if not m:
        return ""
    rest = stmt[m.end():]
    e = re.search(r"\b(" + "|".join(enders) + r")\b", rest, re.I)
    return rest[:e.start()] if e else rest


def where_part(stmt):
    return clause(stmt, "where", ["group\\s+by", "order\\s+by", "limit", "offset", "having",
                                  "union", "returning", "for\\s+update", "window"])


def join_on_parts(stmt):
    return re.findall(r"\bon\b(.*?)(?=\b(?:join|left|right|inner|full|cross|where|group|order|limit|union)\b|$)",
                      stmt, re.I)


def aliases(stmt):
    amap = {}
    for m in re.finditer(r"\b(?:from|join)\s+([a-z_][\w.]*)(?:\s+(?:as\s+)?([a-z_]\w*))?", stmt, re.I):
        table, alias = m.group(1).lower(), (m.group(2) or "").lower()
        if table == "select" or table.startswith("("):
            continue
        amap[table.split(".")[-1]] = table.split(".")[-1]
        if alias and alias not in KEYWORDS:
            amap[alias] = table.split(".")[-1]
    return amap


def shape(stmt):
    s = re.sub(r"'S\d+'", "?", stmt)
    s = re.sub(r"\b\d+(\.\d+)?\b", "?", s)
    s = re.sub(r"\(\s*\?(\s*,\s*\?)*\s*\)", "(?)", s)
    return s.lower()


def review_sql(text, repeat=3, indexes=None):
    stmts, lits = split_statements(text)
    if not stmts:
        raise DataError("no SQL statements found")
    findings = []

    def add(sev, code, n, msg):
        findings.append({"severity": sev, "code": code, "statement": n, "message": msg})

    shapes = defaultdict(list)
    for n, st in enumerate(stmts, 1):
        low = st.lower()
        kind = low.split()[0]
        shapes[shape(st)].append(n)
        where = where_part(st)
        ons = join_on_parts(st)
        filt = " AND ".join([where] + ons)
        if re.search(r"\bselect\s+(distinct\s+)?(\w+\.)?\*", low) or re.search(r",\s*\w+\.\*", low):
            add("MEDIUM", "SELECT_STAR", n, "SELECT * reads every column; list the columns you need so a covering index can serve the query")
        for m in re.finditer(r"\b(" + "|".join(FUNCS) + r")\s*\(\s*([a-z_][\w]*(?:\.[a-z_]\w*)?)\b[^()]*\)\s*(=|<>|!=|<=|>=|<|>|\bin\b|\blike\b|\bbetween\b)",
                             filt, re.I):
            col = m.group(2)
            if col.lower() in KEYWORDS or re.fullmatch(r"S\d+", col):
                continue
            add("HIGH", "FUNC_ON_COLUMN", n, f"{m.group(1)}({col}) in a filter hides {col} from its index; compare the bare column (e.g. a range on the raw value) or add an expression index")
        for m in re.finditer(r"([a-z_][\w.]*)\s*[+\-*/]\s*\d+\s*(=|<|>|<=|>=)", filt, re.I):
            add("HIGH", "FUNC_ON_COLUMN", n, f"arithmetic on {m.group(1)} in a filter; move it to the other side of the comparison")
        for m in re.finditer(r"([a-z_][\w.]*)\s+(not\s+)?(i?like)\s+'S(\d+)'", st, re.I):
            pat = lits[int(m.group(4))]
            if pat[:1] in ("%", "_"):
                add("HIGH", "LEADING_WILDCARD", n, f"{m.group(1)} {m.group(3).upper()} '{pat}' starts with a wildcard, so no B-tree index helps; use full-text search, a trigram index or a reversed column")
        if re.search(r"order\s+by\s+(rand|random|newid)\s*\(\s*\)", low):
            add("HIGH", "ORDER_BY_RANDOM", n, "ORDER BY random sorts every row; pick random ids or use TABLESAMPLE")
        if kind in ("update", "delete") and not where.strip():
            add("HIGH", "NO_WHERE_WRITE", n, f"{kind.upper()} without WHERE touches every row; add a WHERE clause or batch it")
        if where:
            top = where
            while re.search(r"\([^()]*\)", top):
                top = re.sub(r"\([^()]*\)", " _ ", top)
            top = re.sub(r"\bbetween\s+\S+\s+and\b", "between x", top, flags=re.I)
            if re.search(r"\band\b", top, re.I) and re.search(r"\bor\b", top, re.I):
                add("HIGH", "AND_OR_PRECEDENCE", n, "AND and OR are mixed without parentheses; AND binds first, so 'a AND b OR c' returns every row matching c; add parentheses: a AND (b OR c)")
            for group in re.split(r"\band\b", where, flags=re.I):
                if not re.search(r"\bor\b", group, re.I):
                    continue
                cols = re.findall(r"([a-z_][\w.]*)\s*(?:=|<>|!=|<|>|\bin\b|\blike\b)", group, re.I)
                cols = [c.lower() for c in cols if c.lower() not in KEYWORDS and not re.fullmatch(r"s\d+", c.lower())]
                if len(set(cols)) >= 2:
                    add("MEDIUM", "OR_ACROSS_COLUMNS", n, f"OR across {', '.join(sorted(set(cols)))}: one index cannot serve both sides; split into UNION ALL of indexed queries (or check the plan uses a bitmap OR)")
                elif len(cols) >= 2:
                    add("LOW", "OR_SAME_COLUMN", n, f"repeated OR on {cols[0]}; write {cols[0]} IN (...)")
        for m in re.finditer(r"([a-z_][\w.]*)\s*(=|<>|!=|<|>)\s*'S(\d+)'", filt, re.I):
            col = m.group(1).split(".")[-1].lower()
            if ID_COL.search(col) and re.fullmatch(r"-?\d+(\.\d+)?", lits[int(m.group(3))]):
                add("LOW", "QUOTED_NUMBER", n, f"{m.group(1)} compared with the string '{lits[int(m.group(3))]}'; bind it as a number so the driver never sends a text parameter")
        for m in re.finditer(r"([a-z_][\w.]*)\s*(=|<>|!=)\s*(\d{3,})\b", filt, re.I):
            col = m.group(1).split(".")[-1].lower()
            if TEXT_COL.search(col):
                add("MEDIUM", "IMPLICIT_CAST", n, f"{m.group(1)} looks like a text column but is compared with the number {m.group(3)}; MySQL then casts every row and skips the index (PostgreSQL raises a type error); quote the value")
        if re.search(r"\bnot\s+in\s*\(\s*select\b", low):
            add("MEDIUM", "NOT_IN_SUBQUERY", n, "NOT IN (SELECT ...) returns no rows if the subquery yields a NULL and often plans badly; use NOT EXISTS")
        m = re.search(r"\boffset\s+(\d+)", low) or re.search(r"\blimit\s+(\d+)\s*,\s*\d+", low)
        if m and int(m.group(1)) >= 1000:
            add("MEDIUM", "DEEP_OFFSET", n, f"OFFSET {m.group(1)} reads and throws away {m.group(1)} rows; use keyset pagination (WHERE (created_at, id) < (?, ?) ORDER BY ... LIMIT n)")
        if re.search(r"count\s*\(\s*(\*|1)\s*\)\s*(>\s*0|>=\s*1)", low):
            add("LOW", "COUNT_FOR_EXISTS", n, "COUNT(*) > 0 counts every match; EXISTS stops at the first")
        if re.search(r"\bselect\s+distinct\b", low) and re.search(r"\bjoin\b", low):
            add("LOW", "DISTINCT_JOIN", n, "DISTINCT on a join often hides duplicate rows from a one-to-many join; use EXISTS or aggregate first")
        if indexes is not None:
            amap = aliases(st)
            seen = set()
            for m in re.finditer(r"\b([a-z_]\w*)\.([a-z_]\w*)\s*(?:=|<|>|<=|>=|\bin\b|\bbetween\b)", filt, re.I):
                table = amap.get(m.group(1).lower())
                col = m.group(2).lower()
                if not table or (table, col) in seen:
                    continue
                seen.add((table, col))
                if table in indexes and col not in indexes[table]:
                    add("MEDIUM", "NO_INDEX_FOR_FILTER", n, f"{table}.{col} is filtered or joined but no listed index on {table} starts with it")
    for sh, ns in shapes.items():
        if len(ns) >= repeat and ("where" in sh):
            add("HIGH", "N_PLUS_ONE", ns[0], f"statements {', '.join(map(str, ns))} have the same shape with different values ({len(ns)}x); fetch them in one query with IN (...) or a JOIN")
    findings.sort(key=lambda f: (SEV_ORDER[f["severity"]], f["statement"], f["code"]))
    shown = [re.sub(r"'S(\d+)'", lambda m: "'" + lits[int(m.group(1))].replace("'", "''") + "'", st) for st in stmts]
    return shown, findings


def parse_indexes(text):
    idx = defaultdict(set)
    for line in text.splitlines():
        m = re.match(r"\s*([\w.]+)\s*\(\s*([\w\s,]+)\)", line)
        if m:
            idx[m.group(1).split(".")[-1].lower()].add(m.group(2).split(",")[0].strip().lower())
    return idx


def review_explain(text, large=10000):
    findings = []

    def add(sev, code, msg):
        findings.append({"severity": sev, "code": code, "statement": 0, "message": msg})
    lines = text.splitlines()
    if re.search(r"^\s*(\*+ \d+\. row|select_type:)", text, re.M):
        for block in re.split(r"\*+ \d+\. row \*+", text):
            f = dict(re.findall(r"^\s*(\w+):\s*(.*?)\s*$", block, re.M))
            if not f:
                continue
            rows = int(f.get("rows", "0") or 0)
            if f.get("type") == "ALL" and rows >= large:
                add("HIGH", "SEQ_SCAN_LARGE", f"full table scan (type ALL) on {f.get('table')} ~{rows} rows; key={f.get('key', 'NULL')}")
            extra = f.get("Extra", "")
            if "Using filesort" in extra and "Using temporary" in extra:
                add("MEDIUM", "DISK_SORT", f"{f.get('table')}: Using temporary; Using filesort - an index matching GROUP BY/ORDER BY avoids it")
            filtered = float(f.get("filtered", "100") or 100)
            if rows >= 1000 and filtered <= 10:
                add("MEDIUM", "ROWS_REMOVED", f"{f.get('table')}: only {filtered:g}% of {rows} rows pass the filter")
        return findings
    for i, line in enumerate(lines):
        m = re.search(r"(Parallel )?Seq Scan on (\S+).*?rows=(\d+)", line)
        if m:
            act = re.search(r"actual[^)]*rows=(\d+)", line)
            rows = int(act.group(1) if act else m.group(3))
            if rows >= large:
                add("HIGH", "SEQ_SCAN_LARGE", f"Seq Scan on {m.group(2)} returns ~{rows} rows; an index on the filter columns may help")
        m = re.search(r"Rows Removed by Filter:\s*(\d+)", line)
        if m:
            removed = int(m.group(1))
            prev = next((l for l in reversed(lines[:i]) if "actual" in l), "")
            k = re.search(r"actual[^)]*rows=(\d+)", prev)
            kept = int(k.group(1)) if k else 0
            if removed >= 1000 and removed >= 9 * max(kept, 1):
                add("MEDIUM", "ROWS_REMOVED", f"filter removed {removed} rows to keep {kept} ({prev.strip()[:60]}...)")
        m = re.search(r"cost=[\d.]+\.\.[\d.]+ rows=(\d+).*actual time=[\d.]+\.\.[\d.]+ rows=(\d+) loops=(\d+)", line)
        if m:
            est, act, loops = int(m.group(1)), int(m.group(2)), int(m.group(3))
            if max(est, act) >= 100 and max(est, act) >= 10 * max(min(est, act), 1):
                node = line.strip().lstrip("->").strip().split("  ")[0]
                add("MEDIUM", "EST_MISMATCH", f"{node[:50]}: estimated {est} rows, actual {act}; run ANALYZE")
            if loops >= 1000:
                node = line.strip().lstrip("->").strip().split("  ")[0]
                add("LOW", "NESTED_LOOP_MANY", f"{node[:50]} runs {loops} loops; check the join index or consider a hash join")
        if re.search(r"Sort Method: external merge", line):
            add("MEDIUM", "DISK_SORT", "sort spilled to disk (external merge); add an index for ORDER BY or raise work_mem for this query")
    findings.sort(key=lambda f: SEV_ORDER[f["severity"]])
    return findings


def render(path, stmts, findings):
    out = [f"# SQL performance review: {path}", "",
           f"{len(stmts)} statement(s); {sum(f['severity'] == 'HIGH' for f in findings)} HIGH, "
           f"{sum(f['severity'] == 'MEDIUM' for f in findings)} MEDIUM, {sum(f['severity'] == 'LOW' for f in findings)} LOW", ""]
    for n, st in enumerate(stmts, 1):
        out.append(f"{n}. {st[:110]}{'...' if len(st) > 110 else ''}")
    out += ["", "## Findings"]
    if not findings:
        out.append("- none (heuristics only: still check the real plan with EXPLAIN ANALYZE)")
    for f in findings:
        where = f"stmt {f['statement']}" if f["statement"] else "EXPLAIN"
        out.append(f"- {f['severity']} {f['code']} ({where}): {f['message']}")
    return "\n".join(out)


def self_test():
    results = []

    def check(name, cond):
        results.append(cond)
        print(("PASS " if cond else "FAIL ") + name)

    def codes(sql, **kw):
        return [f["code"] for f in review_sql(sql, **kw)[1]]
    check("select star", "SELECT_STAR" in codes("SELECT * FROM users WHERE id = 1"))
    check("alias star", "SELECT_STAR" in codes("SELECT o.* FROM orders o WHERE o.id = 1"))
    check("explicit columns ok", "SELECT_STAR" not in codes("SELECT id, name FROM users WHERE id = 1"))
    check("lower(col) HIGH", "FUNC_ON_COLUMN" in codes("SELECT id FROM users WHERE LOWER(email) = 'a@b.c'"))
    check("year(col) HIGH", "FUNC_ON_COLUMN" in codes("SELECT id FROM orders WHERE YEAR(created_at) = 2026"))
    check("arithmetic HIGH", "FUNC_ON_COLUMN" in codes("SELECT id FROM t WHERE price * 2 > 100"))
    check("function on value side ok", "FUNC_ON_COLUMN" not in codes("SELECT id FROM users WHERE email = LOWER('A@B.C')"))
    check("leading wildcard", "LEADING_WILDCARD" in codes("SELECT id FROM p WHERE name LIKE '%phone%'"))
    check("trailing wildcard ok", "LEADING_WILDCARD" not in codes("SELECT id FROM p WHERE name LIKE 'phone%'"))
    check("wildcard inside string literal ignored", "LEADING_WILDCARD" not in codes("SELECT 'x LIKE %y' AS note FROM p WHERE id = 1"))
    check("N+1 detected", "N_PLUS_ONE" in codes("SELECT name FROM users WHERE id = 1; SELECT name FROM users WHERE id = 2; SELECT name FROM users WHERE id = 3;"))
    check("2 repeats not N+1", "N_PLUS_ONE" not in codes("SELECT name FROM users WHERE id = 1; SELECT name FROM users WHERE id = 2;"))
    check("OR across columns", "OR_ACROSS_COLUMNS" in codes("SELECT id FROM u WHERE email = 'a' OR phone = 'b'"))
    check("OR same column LOW", "OR_SAME_COLUMN" in codes("SELECT id FROM u WHERE status = 'a' OR status = 'b'"))
    check("quoted number LOW", "QUOTED_NUMBER" in codes("SELECT id FROM orders WHERE customer_id = '42'"))
    check("implicit cast phone number", "IMPLICIT_CAST" in codes("SELECT id FROM users WHERE phone = 5551234"))
    check("number id ok", "QUOTED_NUMBER" not in codes("SELECT id FROM orders WHERE customer_id = 42"))
    check("NOT IN subquery", "NOT_IN_SUBQUERY" in codes("SELECT id FROM a WHERE id NOT IN (SELECT a_id FROM b)"))
    check("deep offset", "DEEP_OFFSET" in codes("SELECT id FROM a ORDER BY id LIMIT 20 OFFSET 50000"))
    check("mysql limit a,b offset", "DEEP_OFFSET" in codes("SELECT id FROM a ORDER BY id LIMIT 20000, 20"))
    check("order by rand", "ORDER_BY_RANDOM" in codes("SELECT id FROM a ORDER BY RAND() LIMIT 1"))
    check("delete without where", "NO_WHERE_WRITE" in codes("DELETE FROM sessions"))
    check("AND/OR precedence HIGH", "AND_OR_PRECEDENCE" in codes("SELECT id FROM o WHERE a = 1 AND b = 2 OR b = 3"))
    check("parenthesized OR ok", "AND_OR_PRECEDENCE" not in codes("SELECT id FROM o WHERE a = 1 AND (b = 2 OR b = 3)"))
    check("BETWEEN ... AND not an AND", "AND_OR_PRECEDENCE" not in codes("SELECT id FROM o WHERE d BETWEEN 1 AND 5 OR e = 2"))
    check("literals restored in output", "'mina'" in review_sql("SELECT id FROM u WHERE name = 'mina'")[0][0])
    check("count for exists", "COUNT_FOR_EXISTS" in codes("SELECT CASE WHEN COUNT(*) > 0 THEN 1 END FROM a WHERE b = 1"))
    check("distinct join", "DISTINCT_JOIN" in codes("SELECT DISTINCT u.id FROM users u JOIN orders o ON o.user_id = u.id"))
    idx = parse_indexes("orders(customer_id, created_at)\nusers(id)")
    c = codes("SELECT o.id FROM orders o JOIN users u ON u.id = o.customer_id WHERE o.status = 'paid'", indexes=idx)
    check("no index for filter", c.count("NO_INDEX_FOR_FILTER") == 1)
    check("comments stripped", codes("-- SELECT * FROM x\nSELECT id FROM users WHERE id = 1") == [])
    pg = """Seq Scan on orders  (cost=0.00..25000.00 rows=50 width=8) (actual time=0.1..310.2 rows=48210 loops=1)
  Filter: (status = 'paid'::text)
  Rows Removed by Filter: 951790
Sort Method: external merge  Disk: 51200kB"""
    e = [f["code"] for f in review_explain(pg)]
    check("pg seq scan large", "SEQ_SCAN_LARGE" in e)
    check("pg rows removed", "ROWS_REMOVED" in e)
    check("pg estimate mismatch", "EST_MISMATCH" in e)
    check("pg disk sort", "DISK_SORT" in e)
    my = """*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: orders
         type: ALL
          key: NULL
         rows: 980000
     filtered: 5.00
        Extra: Using where; Using temporary; Using filesort"""
    e = [f["code"] for f in review_explain(my)]
    check("mysql type ALL", "SEQ_SCAN_LARGE" in e and "DISK_SORT" in e and "ROWS_REMOVED" in e)
    try:
        review_sql("  -- only a comment\n")
        check("empty input rejected", False)
    except DataError:
        check("empty input rejected", True)
    print(f"{sum(results)}/{len(results)} passed")
    return 0 if all(results) else 1


def main():
    ap = argparse.ArgumentParser(description="SQL query performance reviewer (heuristic)")
    ap.add_argument("sql", nargs="?", help=".sql file with one or more statements")
    ap.add_argument("--explain", help="EXPLAIN output (PostgreSQL text or MySQL \\G)")
    ap.add_argument("--indexes", help="known indexes, one per line: table(col1, col2)")
    ap.add_argument("--repeat", type=int, default=3, help="N+1 threshold (default 3)")
    ap.add_argument("--large-rows", type=int, default=10000, help="rows for SEQ_SCAN_LARGE (default 10000)")
    ap.add_argument("--json", action="store_true")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args()
    if a.self_test:
        return self_test()
    if not a.sql:
        ap.error("give a .sql file or --self-test")
    try:
        with open(a.sql, encoding="utf-8") as fh:
            text = fh.read()
        idx = None
        if a.indexes:
            with open(a.indexes, encoding="utf-8") as fh:
                idx = parse_indexes(fh.read())
        stmts, findings = review_sql(text, a.repeat, idx)
        if a.explain:
            with open(a.explain, encoding="utf-8") as fh:
                findings += review_explain(fh.read(), a.large_rows)
    except (OSError, DataError) as e:
        print(f"error: {e}", file=sys.stderr)
        return 2
    if a.json:
        print(json.dumps({"statements": stmts, "findings": findings}, indent=2))
    else:
        print(render(a.sql, stmts, findings))
    return 1 if any(f["severity"] == "HIGH" for f in findings) else 0


if __name__ == "__main__":
    sys.exit(main())
PerformanceDatabasePython+1
F@f
0
Redis Caching taste
Taste

Opinionated conventions for using Redis as a cache: keys, TTLs, invalidation and operations.

# Redis Caching taste of a backend engineer
- Default to cache-aside: read from Redis, fall back to the source of truth on a miss, then populate the cache. Confidence: 0.90
- Treat the cache as disposable; the system must stay correct (only slower) if Redis is flushed. Confidence: 0.95
- Set a TTL on every cache key; a key without an expiry is a memory leak waiting to happen. Confidence: 0.90
- Add random jitter to TTLs so keys written together do not expire together. Confidence: 0.85
- Namespace keys as service:entity:id:version (e.g. catalog:product:42:v3) and bump the version on breaking format changes. Confidence: 0.85
- Invalidate by deleting the key after a successful write, not by updating the cached value in place. Confidence: 0.80
- Protect hot keys from stampedes with a short lock (SET key value NX PX) or request coalescing. Confidence: 0.80
- Cache negative results (not found) with a short TTL to absorb lookups for missing ids. Confidence: 0.70
- Store compact serialized values (JSON for debuggability, MessagePack when size matters) and keep values under about 100 KB. Confidence: 0.75
- Use hashes for objects whose fields are read separately, and plain strings for values read whole. Confidence: 0.70
- Never run KEYS in production; use SCAN with a cursor. Confidence: 0.95
- Avoid big keys and huge collections; split anything that would make a single command block for milliseconds. Confidence: 0.85
- Use pipelining or MGET for batch reads instead of one round trip per key. Confidence: 0.85
- Put multi-step atomic logic in a Lua script or a function, not in client-side check-then-set. Confidence: 0.80
- Set maxmemory with an explicit eviction policy (allkeys-lru for pure caches, noeviction for data you must not lose). Confidence: 0.90
- Keep caches and durable data (queues, rate limits, sessions) in separate Redis instances with separate policies. Confidence: 0.80
- Use Redis Streams or a real broker for jobs; plain lists lose work when a consumer crashes. Confidence: 0.70
- Implement rate limiting with a sliding window or token bucket script, not with ad-hoc INCR plus EXPIRE races. Confidence: 0.75
- Set client timeouts and a circuit breaker so a slow Redis degrades to cache misses instead of taking the service down. Confidence: 0.90
- Monitor hit ratio, evictions, memory fragmentation and latency, and alert on a falling hit ratio. Confidence: 0.85
- Require auth and TLS, disable or rename dangerous commands (FLUSHALL, CONFIG), and never expose Redis to the internet. Confidence: 0.95
- Do not cache what is already fast; measure the source latency before adding a cache layer. Confidence: 0.80
PerformanceDatabaseOptimization+2
F@f
0
1 / 2Next