Opinionated technical SEO preferences for web apps: server-rendered HTML, one canonical URL per page, real titles and meta, structured data, sitemaps, fast Core Web Vitals and no accidental noindex.
# Technical SEO taste of a web developer who wants pages search engines can read on the first request - Serve meaningful HTML from the server (SSR or static generation) for every page that should rank; do not rely on client-only rendering. Confidence: 0.90 - Give every indexable page exactly one canonical URL and set a self-referencing rel="canonical" tag. Confidence: 0.90 - Pick one host and trailing-slash style and 301-redirect every other variant (http, www, uppercase, trailing slash) to it. Confidence: 0.90 - Write a unique, specific title tag of roughly 50-60 characters and a meta description for each page from real page data. Confidence: 0.85 - Use one h1 per page and a logical heading order that mirrors the content structure. Confidence: 0.75 - Use clean, readable, lowercase, hyphenated URLs and keep them stable; when one must change, add a permanent redirect. Confidence: 0.90 - Return real HTTP status codes: 404 or 410 for missing content, never a soft 404 that answers 200 with an error page. Confidence: 0.95 - Generate the XML sitemap automatically from the database with lastmod dates and list only canonical, indexable URLs. Confidence: 0.85 - Keep robots.txt small, never block CSS or JS needed to render, and do not use it to hide pages that should be noindexed. Confidence: 0.85 - Make noindex on preview, staging and internal search pages an environment default, and test that production does not ship it. Confidence: 0.95 - Add JSON-LD structured data (Article, Product, BreadcrumbList, Organization) that matches the visible content exactly. Confidence: 0.80 - Set Open Graph and Twitter card tags with an absolute image URL so shared links render a proper preview. Confidence: 0.85 - Treat Core Web Vitals (LCP, INP, CLS) as release criteria and monitor them with real-user data, not only lab scores. Confidence: 0.80 - Give images width and height, descriptive alt text and modern formats, and lazy-load everything below the fold except the LCP image. Confidence: 0.85 - Link between related pages with plain anchor tags and descriptive anchor text; avoid navigation that only works through onClick handlers. Confidence: 0.90 - Handle paginated and filtered lists with crawlable links and canonicalize or noindex parameter combinations that create near-duplicate pages. Confidence: 0.75 - For multilingual sites, use separate URLs per language with hreflang annotations including x-default, never language switching by cookie only. Confidence: 0.85 - Do not hide primary content behind tabs, interactions or infinite scroll that require JavaScript events to load. Confidence: 0.70 - Check Search Console coverage and crawl reports after every major release or migration. Confidence: 0.80 - Prefer fewer, deeper pages over thin auto-generated pages for every keyword variation. Confidence: 0.75
Opinionated Godot 4 project preferences: small composable scenes, typed GDScript, signals up and calls down, autoloads kept rare, resources for data and a clean export pipeline.
# Godot Game Project taste of an indie developer who wants scenes that stay small and reusable - Build the game from small composable scenes, each with a single clear responsibility, instead of one giant level scene. Confidence: 0.90 - Use static typing in GDScript everywhere: typed variables, parameters and return types, and enable the untyped declaration warnings. Confidence: 0.90 - Follow "call down, signal up": parents call methods on children, children emit signals and never reach up the tree. Confidence: 0.90 - Avoid long get_node paths and get_parent chains; use @export node references or unique names (%Name) inside a scene. Confidence: 0.85 - Keep autoloads to a few true global services such as save system, audio and scene transitions, not a dumping ground for state. Confidence: 0.85 - Store game data like items, enemies and levels in custom Resource classes (.tres) instead of hardcoded dictionaries. Confidence: 0.85 - Remember that Resources are shared by default; call duplicate() or enable resource_local_to_scene when each instance needs its own copy. Confidence: 0.80 - Put physics and movement in _physics_process and visuals and input polling in _process, and never assume a fixed frame time. Confidence: 0.85 - Define actions in the Input Map and read Input.is_action_pressed; never check raw keycodes in gameplay code. Confidence: 0.95 - Use a simple state machine (enum with match or state nodes) for player and enemy behavior instead of piles of booleans. Confidence: 0.80 - Set collision layers and masks deliberately and name every layer in Project Settings. Confidence: 0.85 - Organize folders by feature (player/, enemies/, ui/) with each scene next to its script and assets, not by file type. Confidence: 0.75 - Pool frequently spawned objects like bullets and particles when profiling shows instancing cost, not before. Confidence: 0.70 - Use the built-in profiler and monitors before optimizing, and move hot loops to C# or GDExtension only when measured. Confidence: 0.75 - Load big scenes with ResourceLoader.load_threaded_request behind a loading screen instead of freezing the main thread. Confidence: 0.70 - Save games to user:// as versioned JSON or ConfigFile data and never use var_to_bytes with objects for untrusted save files. Confidence: 0.80 - Commit the project with a proper .gitignore that excludes .godot/ and export output, and use Git LFS for large binary assets. Confidence: 0.90 - Keep export presets in version control without secrets and build release exports from CI with a pinned Godot version. Confidence: 0.75 - Write unit tests for pure game logic with GUT or gdUnit4 and keep that logic outside of node scripts where possible. Confidence: 0.65 - Use Tweens and AnimationPlayer for feel and polish instead of hand-written interpolation code in _process. Confidence: 0.80
Opinionated Elixir OTP preferences: supervision trees designed on purpose, GenServers only for state, Task.Supervisor for async work, Registry for naming, telemetry and let-it-crash without silent failures.
# Elixir OTP taste of a backend developer who trusts supervisors more than try/rescue
- Design the supervision tree on paper first and choose one_for_one, rest_for_one or one_for_all deliberately for each supervisor. Confidence: 0.85
- Use a GenServer only when you need state, serialization or a lifecycle; plain modules and functions are the default. Confidence: 0.90
- Never put a single GenServer on the hot path for every request; it becomes a bottleneck, so shard with a pool or use ETS for reads. Confidence: 0.90
- Keep handle_call fast; move slow work to a Task and reply later with GenServer.reply when needed. Confidence: 0.80
- Start fire-and-forget or parallel work under a Task.Supervisor, never with bare spawn. Confidence: 0.95
- Use Task.async_stream with max_concurrency and timeout for bounded parallel work over collections. Confidence: 0.85
- Name dynamic processes through Registry and start them with DynamicSupervisor instead of building atoms from user input. Confidence: 0.95
- Let it crash for unexpected errors, but return {:ok, _} and {:error, _} tuples for expected failures the caller can handle. Confidence: 0.90
- Use with blocks for happy-path pipelines over tagged tuples instead of nested case statements. Confidence: 0.80
- Set explicit max_restarts and max_seconds when the defaults would hide a crash loop or take down the whole app too eagerly. Confidence: 0.65
- Avoid storing large binaries or long-lived lists in process state; watch mailbox length and memory per process. Confidence: 0.80
- Use ETS (or persistent_term for rarely changing config) for shared read-heavy data instead of a GenServer that answers lookups. Confidence: 0.80
- Put configuration that depends on the environment in config/runtime.exs and read it at startup, not with compile-time Application.get_env in module attributes. Confidence: 0.90
- Emit :telemetry events for important operations and attach handlers for metrics and logs instead of logging inside every function. Confidence: 0.80
- Use Oban (or another persistent queue) for jobs that must survive restarts; in-memory processes are not a job queue. Confidence: 0.85
- Write tests with start_supervised! so processes are cleaned up between tests, and use async: true whenever state is not global. Confidence: 0.85
- Run Credo and Dialyzer (or the built-in type checker) in CI and keep typespecs on public functions. Confidence: 0.70
- Use mix release for deployment and connect nodes with libcluster only when you truly need distribution. Confidence: 0.75
- Prefer Phoenix.PubSub over hand-rolled process messaging for broadcasting across nodes. Confidence: 0.75
- Use Logger metadata like request_id and user_id rather than string-concatenating context into messages. Confidence: 0.80Opinionated web image optimization preferences: modern formats with fallbacks, responsive srcset, explicit dimensions, lazy loading below the fold, an image CDN and LCP-first priorities.
# Image Optimization taste of a frontend engineer who watches the LCP number - Serve AVIF first with WebP as the fallback through <picture> or content negotiation, and keep JPEG/PNG only as the last resort. Confidence: 0.85 - Use an image CDN or framework image component that resizes, converts and caches on the fly instead of committing many hand-exported sizes. Confidence: 0.85 - Always set width and height (or aspect-ratio) on every image so the browser reserves space and layout shift stays near zero. Confidence: 1.00 - Use srcset with width descriptors plus an honest sizes attribute; a wrong sizes value silently downloads images twice as large as needed. Confidence: 0.90 - Add loading="lazy" to images below the fold, and never to the hero or LCP image. Confidence: 0.95 - Give the LCP image fetchpriority="high" and preload it when it is set from CSS or discovered late. Confidence: 0.85 - Add decoding="async" to non-critical images so decoding does not block the main thread. Confidence: 0.70 - Cap generated widths at around 2x the largest rendered size; 4000px originals never need to reach a phone. Confidence: 0.85 - Pick quality per format instead of one global value: roughly 50-60 for AVIF, 70-80 for WebP and JPEG, and check visually on real photos. Confidence: 0.75 - Use SVG for icons, logos and simple illustrations, run it through SVGO, and inline only the few icons needed above the fold. Confidence: 0.85 - Never use images for text, buttons or UI chrome that CSS can draw. Confidence: 0.80 - Strip EXIF and GPS metadata from user uploads before serving them, for both privacy and bytes. Confidence: 0.95 - Process user uploads asynchronously into fixed variants and serve originals only to their owner. Confidence: 0.80 - Cache optimized images with long immutable max-age and content-hashed URLs instead of purging caches by hand. Confidence: 0.90 - Use a tiny blurred placeholder or dominant-color background for large images, not a spinner. Confidence: 0.70 - Prefer CSS object-fit and object-position over cropping the same photo into many art-directed files, unless the crop really changes the subject. Confidence: 0.70 - Replace animated GIFs with muted, looping, autoplaying MP4 or WebM video. Confidence: 0.90 - Write meaningful alt text for content images and empty alt="" for decorative ones; never leave alt off. Confidence: 1.00 - Set an image budget per page (for example under 500 KB on mobile for the initial view) and fail CI when Lighthouse or a bundle check goes over it. Confidence: 0.70 - Measure with field data (CrUX or RUM LCP) rather than only a lab run on a fast laptop. Confidence: 0.80 - Do not lazy load images inside carousels with JavaScript tricks when native lazy loading already works. Confidence: 0.65
Opinionated ClickHouse preferences for fast analytics: MergeTree table design, batch ingestion, materialized view rollups, TTLs, quotas and monitoring.
# ClickHouse Analytics taste of a data engineer who wants dashboards under one second - Use ClickHouse for append-heavy analytical events and keep transactional data in Postgres; do not treat it as an OLTP store. Confidence: 0.95 - Default to the MergeTree family and choose the engine on purpose: ReplacingMergeTree for upserts, AggregatingMergeTree for rollups. Confidence: 0.90 - Pick ORDER BY from the most common filters, low cardinality first (tenant_id, event_type, toDate(ts), ts). Confidence: 0.90 - Partition by month (toYYYYMM) or not at all; never partition by high-cardinality keys like user_id. Confidence: 0.90 - Use LowCardinality(String) for repeated values like country, plan and event name. Confidence: 0.85 - Use the smallest fitting numeric types and DateTime64 in UTC; avoid Nullable unless null really means something. Confidence: 0.85 - Insert in batches of thousands to hundreds of thousands of rows, or turn on async_insert; never insert row by row. Confidence: 0.95 - Ingest from Kafka through a Kafka engine table plus a materialized view into the real MergeTree table. Confidence: 0.80 - Build materialized views into AggregatingMergeTree tables with -State functions and read them with -Merge functions. Confidence: 0.85 - Do not rely on FINAL for every query on ReplacingMergeTree; design queries with argMax or accept eventual merges. Confidence: 0.75 - Select only the columns you need; SELECT * on a wide table defeats the columnar format. Confidence: 0.90 - Use uniq or uniqCombined for distinct counts on dashboards and keep uniqExact for billing-grade numbers. Confidence: 0.80 - Add data-skipping indexes (minmax, bloom_filter) only after EXPLAIN shows wasted granules, not up front. Confidence: 0.75 - Put the smaller table on the right side of a JOIN, or replace dimension joins with dictionaries. Confidence: 0.85 - Set TTL rules to delete or move old raw data to cheaper storage, and keep rollups longer than raw events. Confidence: 0.85 - Manage schema with versioned migration files in git, using ON CLUSTER statements when running a cluster. Confidence: 0.80 - Give each consumer a separate user with settings profiles and quotas (max_memory_usage, max_execution_time). Confidence: 0.85 - Watch system.query_log, system.parts and merge activity; alert on too many parts per partition. Confidence: 0.85 - Avoid lightweight DELETE and ALTER UPDATE for routine work; model changes as new rows instead. Confidence: 0.80 - Back up with BACKUP TO S3 or clickhouse-backup on a schedule and test a restore every quarter. Confidence: 0.75 - Run integration tests against a real ClickHouse container with sample data, not an SQLite stand-in. Confidence: 0.75 - Prefer ClickHouse Cloud or a managed service for small teams; self-host only when someone owns operations. Confidence: 0.65
Opinionated preferences for Zig projects: pinned toolchain, build.zig, explicit allocators, error handling, tests and cross-compilation.
# Zig Project taste of a systems developer who likes boring, explicit builds
- Pin the Zig version per project (a .zig-version file or mise/zigup) because the language still breaks between releases. Confidence: 0.90
- Drive everything through build.zig: build, test, run and install steps, with no Makefile or shell wrappers. Confidence: 0.90
- Declare dependencies in build.zig.zon with content hashes and fetch them with zig fetch --save. Confidence: 0.90
- Use b.standardTargetOptions and b.standardOptimizeOption so any target and release mode work from the command line. Confidence: 0.85
- Pass allocators explicitly into every function that allocates; never hide a global allocator. Confidence: 0.95
- Use std.testing.allocator in tests so leaks and double frees fail the test. Confidence: 0.90
- Pair every allocation with defer or errdefer on the very next line. Confidence: 0.90
- Prefer an ArenaAllocator for short-lived request or frame work instead of freeing many small objects. Confidence: 0.80
- Use the GeneralPurposeAllocator (DebugAllocator) in debug builds and check its leak report on exit. Confidence: 0.80
- Return error unions and propagate with try; reserve catch unreachable for cases you can prove. Confidence: 0.90
- Define small, specific error sets for public APIs instead of anyerror. Confidence: 0.80
- Write tests in the same file as the code with test blocks, and run them all with zig build test. Confidence: 0.90
- Keep comptime for real needs such as generics and lookup tables, not for clever metaprogramming. Confidence: 0.80
- Use slices and sentinel-terminated types instead of raw many-item pointers wherever possible. Confidence: 0.85
- Ship ReleaseSafe by default and use ReleaseFast only for measured hot paths. Confidence: 0.75
- Use @import("std").log with scoped loggers instead of std.debug.print in library code. Confidence: 0.75
- Wrap C libraries through @cImport in one small module and expose a Zig-style API from it. Confidence: 0.80
- Use zig cc and zig build to cross-compile C and Zig code from one machine instead of separate toolchains. Confidence: 0.85
- Run zig fmt in CI and fail the build when it would change any file. Confidence: 0.90
- Test in CI on Linux, macOS and Windows, plus at least one cross-compiled target. Confidence: 0.80
- Keep public library APIs in one root.zig and mark everything else non-pub. Confidence: 0.80
- Generate API docs with -femit-docs and publish them with each release. Confidence: 0.65
Finds the slow and failing endpoints in Nginx, Apache or JSON access logs: groups requests into routes, computes p50/p95/p99 latency and 4xx/5xx rates per route, spots 5xx spike minutes and long tails, and flags routes that break a latency target or error budget. Stdlib Python.
---
name: http-access-log-latency-and-error-analyzer
description: Finds the slow and failing endpoints in Nginx, Apache or JSON access logs: groups requests into routes, computes p50/p95/p99 latency and 4xx/5xx rates per route, spots 5xx spike minutes and long tails, and flags routes that break a latency target or error budget. Stdlib Python.
---
# HTTP Access Log Latency and Error Analyzer
You help developers, SREs and on-call engineers answer "which endpoints are slow or failing, since when, and how badly?" straight from the web server's access log, without a metrics stack. Averages hide problems, so you work with percentiles per route, compare them with a latency target and an error budget, and point at the exact minutes and requests worth investigating.
You only read log files the user provides. Access logs contain IP addresses and sometimes user ids or tokens in query strings: keep the analysis local, quote only routes (query strings are dropped by the script) and never paste full raw lines with personal data into tickets or chats.
## Files in this skill
- `scripts/access_log.py` - parses Nginx/Apache combined lines with a trailing request time, or JSON lines; groups requests into routes (`/api/orders/123?x=1` -> `GET /api/orders/:id`), computes count, share, 4xx/5xx rates and p50/p90/p95/p99/max per route, 5xx spike minutes and the slowest requests, and prints flags L01-L06 + E01; `--format text|md|csv|json`; `--self-test` runs 26 checks (Python 3.8+ standard library only)
- `references/log-formats.md` - how to make Nginx, Apache, Caddy, Traefik and load balancers log request time, and which formats the script reads
- `references/latency-triage.md` - how to read percentiles, what each flag usually means, and the next diagnostic step for each
- `templates/latency-report.md` - a short incident or weekly performance note
- `examples/access.log` + `examples/app.jsonl` - a fictional bookshop API during a ten-minute window with a checkout incident
## Workflow
### 1. Get the right log
Ask which server writes the log and for the time window that matters (an incident, a release, a busy hour). Check that every line ends with a request time; if not, help the user add it first (`references/log-formats.md`) or run anyway and accept that only status codes are analyzed (flag L06). Agree the targets: a p95 latency target per route (default 500 ms) and a 5xx budget (default 1%). For rotated logs pass several files at once; for gzip files use `zcat access.log.*.gz > window.log` first.
### 2. Run the analysis
```
python3 scripts/access_log.py /var/log/nginx/access.log
python3 scripts/access_log.py access.log --slo-ms 300 --error-pct 0.5 --min-count 50
python3 scripts/access_log.py access.log --time-unit us # Apache %D (microseconds)
python3 scripts/access_log.py app.jsonl --group-by path --top 0 # exact paths, all routes
python3 scripts/access_log.py access.log --format md > latency.md
python3 scripts/access_log.py access.log --format csv > routes.csv
python3 scripts/access_log.py --self-test
```
Exit code 0 = no flags, 1 = flags present, 2 = unreadable file or no parsable lines.
| Code | Meaning |
|---|---|
| L01 | route p95 is above the latency target (`--slo-ms`) |
| L02 | route 5xx rate is at or above the error budget (`--error-pct`) |
| L03 | route 4xx rate is at or above `--client-error-pct` (broken links, auth, validation, scanners) |
| L04 | a minute with a 5xx spike (at least 5% and 3x the overall 5xx rate, 10+ requests) |
| L05 | long tail: p99 is 5x p50 or more and above the target |
| L06 | no request time in the log, latency cannot be measured |
| E01 | lines that could not be parsed (TLS garbage, a different format, truncated lines) |
Route flags (L01-L03, L05) need at least `--min-count` requests (default 20) so rare routes do not create noise; lower it for short windows.
### 3. Interpret
- Read p95 and p99, not the average: a route with p50 160 ms and p99 3.2 s has a tail problem (one slow dependency, cache misses, lock waits), not a generally slow handler.
- Check whether slow and failing coincide: requests that end in 502 or 504 after about the same time point at an upstream timeout.
- Weight by traffic share: a slow admin report used ten times a day matters less than a 200 ms regression on the product page.
- 4xx on unknown paths like `/wp-login.php` or `/.env` are usually scanners: block or rate limit them rather than debug them.
- Confirm a spike minute against deploys, cron jobs and dependency status before naming a cause.
### 4. Act
Use `references/latency-triage.md` for the next step per flag (tracing a slow route, checking upstream timeouts, connection pools, caching, N+1 queries). Re-run on a log window after the fix and compare the route rows.
### 5. Report
Fill `templates/latency-report.md`: window, overall numbers, the routes that break the target, spike minutes, suspected cause, the fix and the follow-up check.
## Example
```
python3 scripts/access_log.py examples/access.log
```
Result: 222 requests in 10 minutes (1 unparsable TLS line), overall p50 63 ms, p95 914 ms, 5xx 1.8%. `POST /api/checkout` has 17.4% server errors, all four 502s at 14:07 after about 5-6 s (an upstream payment timeout pattern), and p95 5.7 s; `GET /api/search` has p50 160 ms but p95 2.7 s and p99 3.2 s, a long tail; product pages stay at p95 73 ms. Scanner hits on `/wp-login.php`, `/xmlrpc.php` and `/.env` return 404 and are below the flag threshold.
## Limits
- Access logs show what the server saw: time spent in the browser, CDN or client network is not included.
- Percentiles from small samples are unstable; treat routes with few requests as hints.
- Route grouping replaces numbers, UUIDs and long hex strings; slugs such as `/blog/my-post` stay separate (use your framework's route names in JSON logs if you need exact grouping).
- The script does not know your deploy history or dependencies; causes must be confirmed with traces, metrics or application logs.
FILE:references/log-formats.md
# Access log formats and how to log request time
`scripts/access_log.py` reads two kinds of lines and detects them per line, so mixed files work.
## 1. Combined (or common) format with a trailing request time
```
203.0.113.9 - - [27/Nov/2026:14:07:41 +0300] "POST /api/checkout HTTP/1.1" 502 180 "-" "Mozilla/5.0" 5.412
```
The last field is the request time. Default unit is seconds (`--time-unit s`); use `--time-unit ms` or `--time-unit us` for other servers. Lines without a trailing number still count for status codes and traffic, but have no latency (flag L06 if no line has one).
### Nginx
```
log_format timed '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" "$http_user_agent" $request_time';
access_log /var/log/nginx/access.log timed;
```
`$request_time` is the full time from the first client byte to the last byte sent, in seconds with millisecond resolution. `$upstream_response_time` is only the time the backend took; log it as an extra field before `$request_time` if you want to compare them by hand (the script always reads the last field).
### Apache httpd
```
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %D" timed
CustomLog logs/access_log timed
```
`%D` is microseconds: run the script with `--time-unit us`. `%T` is whole seconds and too coarse for latency work.
### Caddy, Traefik, cloud load balancers
- Caddy writes JSON logs by default; convert them to JSON lines with `method`, `path`, `status` and `duration_ms` (Caddy's `duration` is seconds: multiply by 1000), for example with `jq -c '{time: (.ts|todate), method: .request.method, path: .request.uri, status, duration_ms: (.duration*1000)}'`.
- Traefik: enable `accessLog` with `format: json` and map `Duration` (nanoseconds) to `duration_ms`.
- AWS ALB, GCP and Azure load balancers use their own formats; export the method, path, status and total time fields into JSON lines.
## 2. JSON lines
One JSON object per line:
```
{"time": "2026-11-27T14:06:30+03:00", "method": "POST", "path": "/api/orders/5006/refund", "status": 500, "duration_ms": 2140, "bytes": 120}
```
Required: `method`, `path`, `status`. Latency from `duration_ms`, `request_time_ms` or `request_time` (seconds). `time` (ISO 8601) enables spike minutes. If your framework logs a route template (for example `/api/orders/{id}`), put it in `path` and run with `--group-by path` for exact grouping.
## Time zones and windows
Spike minutes use the time as written in the log, including its offset. Cut the window before running (for example `awk '/27\/Nov\/2026:14:0/' access.log > window.log`) so the overall numbers describe the period you care about.
## Privacy
Access logs hold IP addresses and sometimes tokens or emails in query strings. The script drops query strings from routes, but the "slowest requests" list shows full targets; redact them before sharing a report outside the team.
FILE:references/latency-triage.md
# Reading the results and what to do next
## Percentiles in one minute
- p50 = the typical request; p95 = 1 in 20 requests is slower; p99 = 1 in 100. Users who click often hit the p95/p99 several times a session.
- The script uses nearest-rank percentiles: with 40 requests, p95 is the 38th fastest request. Below about 100 requests per route, p99 is just the slowest one or two requests.
- Compare windows of the same length and similar traffic; a quiet night and a sale hour are not comparable.
## Flags and the next step
| Flag | Usual causes | Next step |
|---|---|---|
| L01 p95 above target | slow database queries, missing indexes, N+1 queries, large responses, cold caches, CPU saturation | trace a few of the slowest requests; check query counts and response size; compare with the previous release |
| L02 5xx over budget | crashes, upstream errors (502), timeouts (504), overload (503) | group the errors by status and minute; read application logs for the same minutes; check recent deploys and dependency status pages |
| L03 many 4xx | broken links (404), expired sessions (401), permission changes (403), validation errors (400/422), scanners | look at the paths and user agents; fix links or clients; rate limit or block scanner paths |
| L04 5xx spike minute | deploy or restart, cron job, failing dependency, traffic burst | line the minute up with deploy logs, cron schedules and upstream incidents |
| L05 long tail | one slow dependency on some requests, lock contention, garbage collection pauses, retries, cache misses | split the route by parameters (for example search terms) in the raw lines; add timing logs around external calls |
| L06 no latency | the log format has no request time | add `$request_time` or `%D` (see `log-formats.md`) |
| E01 unparsable | TLS handshakes on the HTTP port, other vhosts with another format, truncated lines | check a few lines; a handful is normal |
## Patterns worth recognizing
- Errors that all take about the same long time (for example 5-6 s or 30 s) usually mean an upstream timeout: check the proxy and client timeout settings and the dependency itself.
- Fast errors (a few ms) mean the request was rejected early: auth, validation, rate limiting or a crashing handler.
- p50 up for every route at once points at shared infrastructure (database, CPU, network), not at one handler.
- A slow route with a tiny share of traffic can wait; a 20 percent regression on the busiest route usually cannot.
## Setting targets
Start with what users notice: about 200-300 ms p95 for API reads behind interactive pages, 500-1000 ms for writes such as checkout, longer for reports and exports. Agree per route group and write them down next to the error budget (for example 99.5 percent non-5xx per 30 days). Pass them with `--slo-ms` and `--error-pct`, or run the script per route group with different settings.
FILE:templates/latency-report.md
# Latency and error report: {{service}} ({{window}})
Prepared by: {{author}} | Log source: {{log_source}} | Targets: p95 <= {{slo_ms}} ms, 5xx < {{error_pct}}%
## Summary
- Requests: {{requests}} | Overall p50 / p95 / p99: {{p50}} / {{p95}} / {{p99}} ms | 5xx: {{rate_5xx}}%
- Verdict: {{verdict}} (within targets / degraded / incident)
## Routes outside the targets
| Route | Share | p95 | p99 | 5xx | Flag |
|---|---|---|---|---|---|
| {{route}} | {{share}} | {{p95_route}} | {{p99_route}} | {{rate_5xx_route}} | {{flag}} |
## Spike minutes
- {{minute}}: {{errors}} of {{requests_minute}} requests failed ({{rate}}%). Matching event: {{event}}
## Cause
- Confirmed: {{confirmed_cause}}
- Suspected, still to check: {{suspected_cause}}
## Actions
| Action | Owner | Due | Done when |
|---|---|---|---|
| {{action}} | {{owner}} | {{due}} | {{done_when}} |
## Follow-up check
Re-run `access_log.py` on {{followup_window}} and compare these routes: {{routes_to_compare}}.
FILE:examples/access.log
203.0.113.30 - - [27/Nov/2026:14:00:00 +0300] "GET /api/search?q=atlas HTTP/1.1" 200 3058 "-" "Mozilla/5.0" 0.206
203.0.113.29 - - [27/Nov/2026:14:00:01 +0300] "GET /api/products/247 HTTP/1.1" 200 1273 "-" "Mozilla/5.0" 0.067
203.0.113.19 - - [27/Nov/2026:14:00:02 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.081
203.0.113.12 - - [27/Nov/2026:14:00:04 +0300] "GET /api/search?q=tolkien HTTP/1.1" 200 3779 "-" "Mozilla/5.0" 2.551
203.0.113.7 - - [27/Nov/2026:14:00:12 +0300] "GET /api/products/594 HTTP/1.1" 200 1449 "-" "Mozilla/5.0" 0.039
203.0.113.36 - - [27/Nov/2026:14:00:14 +0300] "GET /api/products/862 HTTP/1.1" 200 1634 "-" "Mozilla/5.0" 0.023
203.0.113.15 - - [27/Nov/2026:14:00:20 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.079
203.0.113.19 - - [27/Nov/2026:14:00:23 +0300] "GET /api/search?q=dune HTTP/1.1" 200 3506 "-" "Mozilla/5.0" 0.199
203.0.113.30 - - [27/Nov/2026:14:00:23 +0300] "POST /api/login HTTP/1.1" 401 90 "-" "Mozilla/5.0" 0.124
203.0.113.31 - - [27/Nov/2026:14:00:24 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.004
203.0.113.8 - - [27/Nov/2026:14:00:24 +0300] "GET /api/products/468 HTTP/1.1" 200 2023 "-" "Mozilla/5.0" 0.067
203.0.113.10 - - [27/Nov/2026:14:00:26 +0300] "GET /api/products/530 HTTP/1.1" 200 2156 "-" "Mozilla/5.0" 0.037
203.0.113.30 - - [27/Nov/2026:14:00:29 +0300] "GET /api/products/217 HTTP/1.1" 200 1095 "-" "Mozilla/5.0" 0.074
203.0.113.31 - - [27/Nov/2026:14:00:33 +0300] "GET /api/products/226 HTTP/1.1" 200 1364 "-" "Mozilla/5.0" 0.068
203.0.113.18 - - [27/Nov/2026:14:00:34 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.633
203.0.113.35 - - [27/Nov/2026:14:00:35 +0300] "GET /api/search?q=silo HTTP/1.1" 200 5195 "-" "Mozilla/5.0" 0.201
203.0.113.28 - - [27/Nov/2026:14:00:38 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.063
203.0.113.8 - - [27/Nov/2026:14:00:38 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.004
203.0.113.32 - - [27/Nov/2026:14:00:42 +0300] "GET /api/products/440 HTTP/1.1" 200 2174 "-" "Mozilla/5.0" 0.031
203.0.113.34 - - [27/Nov/2026:14:00:49 +0300] "POST /api/login HTTP/1.1" 200 90 "-" "Mozilla/5.0" 0.154
203.0.113.11 - - [27/Nov/2026:14:00:56 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.867
203.0.113.19 - - [27/Nov/2026:14:00:57 +0300] "GET /api/products/364 HTTP/1.1" 200 1535 "-" "Mozilla/5.0" 0.054
203.0.113.32 - - [27/Nov/2026:14:01:03 +0300] "GET /api/products/866 HTTP/1.1" 200 972 "-" "Mozilla/5.0" 0.069
203.0.113.38 - - [27/Nov/2026:14:01:03 +0300] "GET /api/search?q=silo HTTP/1.1" 200 8586 "-" "Mozilla/5.0" 0.218
203.0.113.9 - - [27/Nov/2026:14:01:04 +0300] "GET /api/search?q=cookbook HTTP/1.1" 200 7337 "-" "Mozilla/5.0" 0.205
203.0.113.20 - - [27/Nov/2026:14:01:09 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.043
203.0.113.14 - - [27/Nov/2026:14:01:13 +0300] "GET /api/products/402 HTTP/1.1" 200 1613 "-" "Mozilla/5.0" 0.046
203.0.113.21 - - [27/Nov/2026:14:01:19 +0300] "GET /api/products/890 HTTP/1.1" 200 2173 "-" "Mozilla/5.0" 0.052
203.0.113.18 - - [27/Nov/2026:14:01:21 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.669
203.0.113.7 - - [27/Nov/2026:14:01:26 +0300] "GET /api/products/887 HTTP/1.1" 200 1163 "-" "Mozilla/5.0" 0.037
203.0.113.8 - - [27/Nov/2026:14:01:30 +0300] "GET /api/products/289 HTTP/1.1" 200 1027 "-" "Mozilla/5.0" 0.041
203.0.113.29 - - [27/Nov/2026:14:01:31 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.081
203.0.113.34 - - [27/Nov/2026:14:01:31 +0300] "GET /api/search?q=silo HTTP/1.1" 200 6323 "-" "Mozilla/5.0" 2.565
203.0.113.30 - - [27/Nov/2026:14:01:34 +0300] "GET /api/products/343 HTTP/1.1" 200 1821 "-" "Mozilla/5.0" 0.057
203.0.113.9 - - [27/Nov/2026:14:01:34 +0300] "GET /api/products/545 HTTP/1.1" 200 1119 "-" "Mozilla/5.0" 0.020
203.0.113.15 - - [27/Nov/2026:14:01:36 +0300] "GET /api/search?q=tolkien HTTP/1.1" 200 3632 "-" "Mozilla/5.0" 0.158
203.0.113.33 - - [27/Nov/2026:14:01:38 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.056
203.0.113.14 - - [27/Nov/2026:14:01:39 +0300] "GET /api/products/872 HTTP/1.1" 200 976 "-" "Mozilla/5.0" 0.065
203.0.113.13 - - [27/Nov/2026:14:01:40 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.878
203.0.113.6 - - [27/Nov/2026:14:01:40 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.002
203.0.113.30 - - [27/Nov/2026:14:01:45 +0300] "GET /api/products/185 HTTP/1.1" 200 1629 "-" "Mozilla/5.0" 0.064
203.0.113.22 - - [27/Nov/2026:14:01:51 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.003
203.0.113.14 - - [27/Nov/2026:14:02:03 +0300] "GET /api/search?q=tolkien HTTP/1.1" 200 6697 "-" "Mozilla/5.0" 0.094
203.0.113.8 - - [27/Nov/2026:14:02:06 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.786
203.0.113.38 - - [27/Nov/2026:14:02:08 +0300] "GET /api/products/415 HTTP/1.1" 200 1272 "-" "Mozilla/5.0" 0.064
203.0.113.13 - - [27/Nov/2026:14:02:10 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.047
203.0.113.18 - - [27/Nov/2026:14:02:10 +0300] "GET /api/products/452 HTTP/1.1" 200 908 "-" "Mozilla/5.0" 0.045
203.0.113.27 - - [27/Nov/2026:14:02:10 +0300] "GET /api/products/729 HTTP/1.1" 200 2011 "-" "Mozilla/5.0" 0.052
203.0.113.5 - - [27/Nov/2026:14:02:10 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.005
203.0.113.10 - - [27/Nov/2026:14:02:13 +0300] "GET /api/products/653 HTTP/1.1" 200 1808 "-" "Mozilla/5.0" 0.055
203.0.113.31 - - [27/Nov/2026:14:02:15 +0300] "POST /api/login HTTP/1.1" 200 90 "-" "Mozilla/5.0" 0.148
203.0.113.30 - - [27/Nov/2026:14:02:16 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.049
203.0.113.25 - - [27/Nov/2026:14:02:17 +0300] "GET /api/products/679 HTTP/1.1" 200 2112 "-" "Mozilla/5.0" 0.035
203.0.113.25 - - [27/Nov/2026:14:02:17 +0300] "GET /api/products/963 HTTP/1.1" 200 1469 "-" "Mozilla/5.0" 0.024
203.0.113.12 - - [27/Nov/2026:14:02:22 +0300] "GET /api/search?q=atlas HTTP/1.1" 200 4290 "-" "Mozilla/5.0" 0.218
203.0.113.38 - - [27/Nov/2026:14:02:30 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.681
203.0.113.22 - - [27/Nov/2026:14:02:31 +0300] "GET /api/search?q=silo HTTP/1.1" 200 6906 "-" "Mozilla/5.0" 0.144
203.0.113.77 - - [27/Nov/2026:14:03:12 +0300] "\x16\x03\x01\x00" 400 157 "-" "-"
203.0.113.17 - - [27/Nov/2026:14:02:37 +0300] "GET /api/search?q=cookbook HTTP/1.1" 200 5341 "-" "Mozilla/5.0" 0.175
203.0.113.39 - - [27/Nov/2026:14:02:43 +0300] "GET /api/products/210 HTTP/1.1" 200 1287 "-" "Mozilla/5.0" 0.041
203.0.113.22 - - [27/Nov/2026:14:02:47 +0300] "GET /api/products/412 HTTP/1.1" 200 2007 "-" "Mozilla/5.0" 0.024
203.0.113.39 - - [27/Nov/2026:14:02:48 +0300] "GET /api/products/681 HTTP/1.1" 200 1777 "-" "Mozilla/5.0" 0.043
203.0.113.33 - - [27/Nov/2026:14:02:49 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.057
203.0.113.29 - - [27/Nov/2026:14:02:52 +0300] "POST /api/login HTTP/1.1" 200 90 "-" "Mozilla/5.0" 0.143
203.0.113.17 - - [27/Nov/2026:14:02:59 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.003
203.0.113.38 - - [27/Nov/2026:14:03:00 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.048
203.0.113.35 - - [27/Nov/2026:14:03:01 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.691
203.0.113.12 - - [27/Nov/2026:14:03:06 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.802
203.0.113.25 - - [27/Nov/2026:14:03:09 +0300] "GET /api/search?q=cookbook HTTP/1.1" 200 5078 "-" "Mozilla/5.0" 0.149
203.0.113.21 - - [27/Nov/2026:14:03:11 +0300] "GET /api/products/676 HTTP/1.1" 200 1190 "-" "Mozilla/5.0" 0.068
203.0.113.30 - - [27/Nov/2026:14:03:13 +0300] "GET /api/products/946 HTTP/1.1" 200 1083 "-" "Mozilla/5.0" 0.065
203.0.113.27 - - [27/Nov/2026:14:03:14 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.060
203.0.113.38 - - [27/Nov/2026:14:03:14 +0300] "GET /api/products/209 HTTP/1.1" 200 1911 "-" "Mozilla/5.0" 0.075
203.0.113.10 - - [27/Nov/2026:14:03:15 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.002
203.0.113.17 - - [27/Nov/2026:14:03:16 +0300] "GET /api/products/465 HTTP/1.1" 200 1938 "-" "Mozilla/5.0" 0.039
203.0.113.17 - - [27/Nov/2026:14:03:20 +0300] "GET /api/search?q=cookbook HTTP/1.1" 200 6520 "-" "Mozilla/5.0" 0.151
203.0.113.12 - - [27/Nov/2026:14:03:24 +0300] "GET /wp-login.php HTTP/1.1" 404 153 "-" "python-requests/2.31" 0.001
203.0.113.18 - - [27/Nov/2026:14:03:25 +0300] "GET /api/search?q=dune HTTP/1.1" 200 6928 "-" "Mozilla/5.0" 0.093
203.0.113.38 - - [27/Nov/2026:14:03:26 +0300] "GET /api/products/906 HTTP/1.1" 200 1205 "-" "Mozilla/5.0" 0.070
203.0.113.20 - - [27/Nov/2026:14:03:29 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.004
203.0.113.37 - - [27/Nov/2026:14:03:35 +0300] "GET /api/search?q=silo HTTP/1.1" 200 4848 "-" "Mozilla/5.0" 0.206
203.0.113.29 - - [27/Nov/2026:14:03:37 +0300] "GET /api/products/107 HTTP/1.1" 200 1853 "-" "Mozilla/5.0" 0.046
203.0.113.17 - - [27/Nov/2026:14:03:39 +0300] "GET /api/products/694 HTTP/1.1" 200 2362 "-" "Mozilla/5.0" 0.042
203.0.113.9 - - [27/Nov/2026:14:03:40 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.069
203.0.113.19 - - [27/Nov/2026:14:03:43 +0300] "GET /api/products/890 HTTP/1.1" 200 2053 "-" "Mozilla/5.0" 0.021
203.0.113.21 - - [27/Nov/2026:14:03:45 +0300] "GET /api/products/287 HTTP/1.1" 200 1703 "-" "Mozilla/5.0" 0.023
203.0.113.7 - - [27/Nov/2026:14:03:49 +0300] "GET /xmlrpc.php HTTP/1.1" 404 153 "-" "python-requests/2.31" 0.001
203.0.113.31 - - [27/Nov/2026:14:03:58 +0300] "GET /.env HTTP/1.1" 404 153 "-" "python-requests/2.31" 0.001
203.0.113.11 - - [27/Nov/2026:14:04:03 +0300] "GET /api/search?q=atlas HTTP/1.1" 200 8767 "-" "Mozilla/5.0" 0.113
203.0.113.28 - - [27/Nov/2026:14:04:03 +0300] "POST /api/login HTTP/1.1" 200 90 "-" "Mozilla/5.0" 0.174
203.0.113.10 - - [27/Nov/2026:14:04:11 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.030
203.0.113.15 - - [27/Nov/2026:14:04:13 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.724
203.0.113.28 - - [27/Nov/2026:14:04:15 +0300] "GET /api/search?q=tolkien HTTP/1.1" 200 7269 "-" "Mozilla/5.0" 0.130
203.0.113.28 - - [27/Nov/2026:14:04:19 +0300] "GET /.env HTTP/1.1" 404 153 "-" "python-requests/2.31" 0.001
203.0.113.12 - - [27/Nov/2026:14:04:20 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.067
203.0.113.22 - - [27/Nov/2026:14:04:20 +0300] "GET /api/products/268 HTTP/1.1" 200 1504 "-" "Mozilla/5.0" 0.046
203.0.113.16 - - [27/Nov/2026:14:04:30 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.002
203.0.113.25 - - [27/Nov/2026:14:04:32 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.062
203.0.113.20 - - [27/Nov/2026:14:04:34 +0300] "GET /api/products/915 HTTP/1.1" 200 1459 "-" "Mozilla/5.0" 0.021
203.0.113.15 - - [27/Nov/2026:14:04:36 +0300] "GET /api/search?q=tolkien HTTP/1.1" 200 7158 "-" "Mozilla/5.0" 2.711
203.0.113.21 - - [27/Nov/2026:14:04:37 +0300] "GET /xmlrpc.php HTTP/1.1" 404 153 "-" "python-requests/2.31" 0.001
203.0.113.12 - - [27/Nov/2026:14:04:38 +0300] "GET /api/products/773 HTTP/1.1" 200 1042 "-" "Mozilla/5.0" 0.074
203.0.113.35 - - [27/Nov/2026:14:04:42 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.004
203.0.113.13 - - [27/Nov/2026:14:04:44 +0300] "GET /wp-login.php HTTP/1.1" 404 153 "-" "python-requests/2.31" 0.001
203.0.113.25 - - [27/Nov/2026:14:04:47 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.841
203.0.113.15 - - [27/Nov/2026:14:04:49 +0300] "GET /api/products/547 HTTP/1.1" 200 1202 "-" "Mozilla/5.0" 0.073
203.0.113.8 - - [27/Nov/2026:14:04:49 +0300] "GET /api/products/660 HTTP/1.1" 200 935 "-" "Mozilla/5.0" 0.038
203.0.113.12 - - [27/Nov/2026:14:04:50 +0300] "GET /api/search?q=dune HTTP/1.1" 200 8341 "-" "Mozilla/5.0" 0.102
203.0.113.37 - - [27/Nov/2026:14:04:50 +0300] "GET /api/products/210 HTTP/1.1" 200 1589 "-" "Mozilla/5.0" 0.063
203.0.113.15 - - [27/Nov/2026:14:04:53 +0300] "GET /api/products/864 HTTP/1.1" 200 1718 "-" "Mozilla/5.0" 0.040
203.0.113.39 - - [27/Nov/2026:14:04:55 +0300] "POST /api/login HTTP/1.1" 200 90 "-" "Mozilla/5.0" 0.129
203.0.113.23 - - [27/Nov/2026:14:04:56 +0300] "GET /api/products/751 HTTP/1.1" 200 1922 "-" "Mozilla/5.0" 0.035
203.0.113.12 - - [27/Nov/2026:14:04:57 +0300] "GET /api/products/404 HTTP/1.1" 200 1495 "-" "Mozilla/5.0" 0.046
203.0.113.24 - - [27/Nov/2026:14:05:05 +0300] "GET /wp-login.php HTTP/1.1" 404 153 "-" "python-requests/2.31" 0.001
203.0.113.35 - - [27/Nov/2026:14:05:09 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.043
203.0.113.33 - - [27/Nov/2026:14:05:20 +0300] "GET /api/search?q=atlas HTTP/1.1" 200 8858 "-" "Mozilla/5.0" 1.611
203.0.113.24 - - [27/Nov/2026:14:05:22 +0300] "GET /xmlrpc.php HTTP/1.1" 404 153 "-" "python-requests/2.31" 0.001
203.0.113.32 - - [27/Nov/2026:14:05:24 +0300] "GET /api/products/651 HTTP/1.1" 200 1887 "-" "Mozilla/5.0" 0.029
203.0.113.29 - - [27/Nov/2026:14:05:25 +0300] "GET /api/products/444 HTTP/1.1" 200 2215 "-" "Mozilla/5.0" 0.056
203.0.113.38 - - [27/Nov/2026:14:05:29 +0300] "GET /api/products/970 HTTP/1.1" 200 1910 "-" "Mozilla/5.0" 0.047
203.0.113.38 - - [27/Nov/2026:14:05:30 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.004
203.0.113.13 - - [27/Nov/2026:14:05:31 +0300] "GET /api/products/508 HTTP/1.1" 200 1583 "-" "Mozilla/5.0" 0.043
203.0.113.30 - - [27/Nov/2026:14:05:31 +0300] "GET /api/products/356 HTTP/1.1" 200 1223 "-" "Mozilla/5.0" 0.070
203.0.113.18 - - [27/Nov/2026:14:05:32 +0300] "GET /api/search?q=atlas HTTP/1.1" 200 3374 "-" "Mozilla/5.0" 0.121
203.0.113.14 - - [27/Nov/2026:14:05:34 +0300] "GET /api/products/518 HTTP/1.1" 200 1305 "-" "Mozilla/5.0" 0.048
203.0.113.14 - - [27/Nov/2026:14:05:35 +0300] "GET /api/search?q=atlas HTTP/1.1" 200 6801 "-" "Mozilla/5.0" 0.126
203.0.113.21 - - [27/Nov/2026:14:05:37 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.655
203.0.113.30 - - [27/Nov/2026:14:05:42 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.914
203.0.113.31 - - [27/Nov/2026:14:05:45 +0300] "GET /api/products/515 HTTP/1.1" 200 2005 "-" "Mozilla/5.0" 0.032
203.0.113.14 - - [27/Nov/2026:14:05:47 +0300] "GET /.env HTTP/1.1" 404 153 "-" "python-requests/2.31" 0.001
203.0.113.24 - - [27/Nov/2026:14:05:49 +0300] "GET /api/products/748 HTTP/1.1" 200 1005 "-" "Mozilla/5.0" 0.028
203.0.113.38 - - [27/Nov/2026:14:05:52 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.090
203.0.113.13 - - [27/Nov/2026:14:05:53 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.002
203.0.113.18 - - [27/Nov/2026:14:05:54 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.089
203.0.113.20 - - [27/Nov/2026:14:05:55 +0300] "GET /api/products/805 HTTP/1.1" 200 1019 "-" "Mozilla/5.0" 0.032
203.0.113.9 - - [27/Nov/2026:14:05:58 +0300] "GET /api/search?q=tolkien HTTP/1.1" 200 7714 "-" "Mozilla/5.0" 0.134
203.0.113.6 - - [27/Nov/2026:14:06:05 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.056
203.0.113.8 - - [27/Nov/2026:14:06:06 +0300] "GET /api/products/663 HTTP/1.1" 200 1169 "-" "Mozilla/5.0" 0.034
203.0.113.7 - - [27/Nov/2026:14:06:07 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.005
203.0.113.14 - - [27/Nov/2026:14:06:09 +0300] "GET /api/products/501 HTTP/1.1" 200 1005 "-" "Mozilla/5.0" 0.035
203.0.113.31 - - [27/Nov/2026:14:06:09 +0300] "GET /api/products/622 HTTP/1.1" 200 1838 "-" "Mozilla/5.0" 0.045
203.0.113.38 - - [27/Nov/2026:14:06:10 +0300] "POST /api/login HTTP/1.1" 200 90 "-" "Mozilla/5.0" 0.148
203.0.113.8 - - [27/Nov/2026:14:06:15 +0300] "GET /api/products/526 HTTP/1.1" 200 1208 "-" "Mozilla/5.0" 0.043
203.0.113.27 - - [27/Nov/2026:14:06:23 +0300] "GET /api/products/784 HTTP/1.1" 200 980 "-" "Mozilla/5.0" 0.064
203.0.113.11 - - [27/Nov/2026:14:06:24 +0300] "GET /api/products/866 HTTP/1.1" 200 1171 "-" "Mozilla/5.0" 0.038
203.0.113.30 - - [27/Nov/2026:14:06:24 +0300] "GET /api/products/953 HTTP/1.1" 200 2340 "-" "Mozilla/5.0" 0.042
203.0.113.30 - - [27/Nov/2026:14:06:26 +0300] "GET /api/search?q=dune HTTP/1.1" 200 5446 "-" "Mozilla/5.0" 3.177
203.0.113.29 - - [27/Nov/2026:14:06:28 +0300] "POST /api/login HTTP/1.1" 401 90 "-" "Mozilla/5.0" 0.123
203.0.113.10 - - [27/Nov/2026:14:06:31 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.087
203.0.113.26 - - [27/Nov/2026:14:06:33 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.645
203.0.113.33 - - [27/Nov/2026:14:06:35 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.005
203.0.113.37 - - [27/Nov/2026:14:06:41 +0300] "GET /api/products/200 HTTP/1.1" 200 1293 "-" "Mozilla/5.0" 0.041
203.0.113.15 - - [27/Nov/2026:14:06:42 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.038
203.0.113.35 - - [27/Nov/2026:14:06:43 +0300] "GET /api/products/531 HTTP/1.1" 200 943 "-" "Mozilla/5.0" 0.034
203.0.113.22 - - [27/Nov/2026:14:06:46 +0300] "GET /api/search?q=atlas HTTP/1.1" 200 5404 "-" "Mozilla/5.0" 0.127
203.0.113.14 - - [27/Nov/2026:14:06:49 +0300] "GET /api/search?q=dune HTTP/1.1" 200 4809 "-" "Mozilla/5.0" 1.899
203.0.113.9 - - [27/Nov/2026:14:06:52 +0300] "GET /api/search?q=atlas HTTP/1.1" 200 8222 "-" "Mozilla/5.0" 0.143
203.0.113.23 - - [27/Nov/2026:14:06:58 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.639
203.0.113.12 - - [27/Nov/2026:14:07:02 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.583
203.0.113.26 - - [27/Nov/2026:14:07:03 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.069
203.0.113.39 - - [27/Nov/2026:14:07:05 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.006
203.0.113.15 - - [27/Nov/2026:14:07:08 +0300] "GET /api/search?q=dune HTTP/1.1" 200 5621 "-" "Mozilla/5.0" 0.209
203.0.113.20 - - [27/Nov/2026:14:07:12 +0300] "GET /api/products/812 HTTP/1.1" 200 1391 "-" "Mozilla/5.0" 0.064
203.0.113.25 - - [27/Nov/2026:14:07:14 +0300] "GET /api/products/725 HTTP/1.1" 200 1832 "-" "Mozilla/5.0" 0.046
203.0.113.7 - - [27/Nov/2026:14:07:15 +0300] "POST /api/checkout HTTP/1.1" 502 180 "-" "Mozilla/5.0" 5.749
203.0.113.39 - - [27/Nov/2026:14:07:17 +0300] "GET /api/products/110 HTTP/1.1" 200 2074 "-" "Mozilla/5.0" 0.073
203.0.113.39 - - [27/Nov/2026:14:07:21 +0300] "GET /api/search?q=dune HTTP/1.1" 200 7568 "-" "Mozilla/5.0" 0.160
203.0.113.28 - - [27/Nov/2026:14:07:27 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.006
203.0.113.37 - - [27/Nov/2026:14:07:27 +0300] "GET /api/products/625 HTTP/1.1" 200 1057 "-" "Mozilla/5.0" 0.032
203.0.113.26 - - [27/Nov/2026:14:07:37 +0300] "GET /api/products/217 HTTP/1.1" 200 2046 "-" "Mozilla/5.0" 0.021
203.0.113.32 - - [27/Nov/2026:14:07:39 +0300] "POST /api/checkout HTTP/1.1" 502 180 "-" "Mozilla/5.0" 5.107
203.0.113.25 - - [27/Nov/2026:14:07:41 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.062
203.0.113.34 - - [27/Nov/2026:14:07:42 +0300] "GET /api/search?q=silo HTTP/1.1" 200 3934 "-" "Mozilla/5.0" 0.152
203.0.113.12 - - [27/Nov/2026:14:07:44 +0300] "GET /api/products/185 HTTP/1.1" 200 1274 "-" "Mozilla/5.0" 0.039
203.0.113.18 - - [27/Nov/2026:14:07:47 +0300] "POST /api/checkout HTTP/1.1" 502 180 "-" "Mozilla/5.0" 5.665
203.0.113.23 - - [27/Nov/2026:14:07:48 +0300] "POST /api/checkout HTTP/1.1" 502 180 "-" "Mozilla/5.0" 5.248
203.0.113.29 - - [27/Nov/2026:14:07:49 +0300] "GET /api/search?q=tolkien HTTP/1.1" 200 3422 "-" "Mozilla/5.0" 0.098
203.0.113.35 - - [27/Nov/2026:14:07:54 +0300] "GET /api/products/982 HTTP/1.1" 200 2214 "-" "Mozilla/5.0" 0.049
203.0.113.36 - - [27/Nov/2026:14:07:54 +0300] "GET /api/products/756 HTTP/1.1" 200 1335 "-" "Mozilla/5.0" 0.073
203.0.113.27 - - [27/Nov/2026:14:07:56 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.054
203.0.113.18 - - [27/Nov/2026:14:07:59 +0300] "GET /api/products/756 HTTP/1.1" 200 1947 "-" "Mozilla/5.0" 0.066
203.0.113.31 - - [27/Nov/2026:14:08:07 +0300] "GET /api/products/773 HTTP/1.1" 200 1918 "-" "Mozilla/5.0" 0.026
203.0.113.39 - - [27/Nov/2026:14:08:08 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.738
203.0.113.38 - - [27/Nov/2026:14:08:12 +0300] "GET /api/products/894 HTTP/1.1" 200 908 "-" "Mozilla/5.0" 0.028
203.0.113.20 - - [27/Nov/2026:14:08:16 +0300] "GET /api/search?q=dune HTTP/1.1" 200 7250 "-" "Mozilla/5.0" 0.160
203.0.113.21 - - [27/Nov/2026:14:08:16 +0300] "GET /api/products/105 HTTP/1.1" 200 1282 "-" "Mozilla/5.0" 0.056
203.0.113.25 - - [27/Nov/2026:14:08:17 +0300] "GET /api/search?q=dune HTTP/1.1" 200 4620 "-" "Mozilla/5.0" 0.201
203.0.113.14 - - [27/Nov/2026:14:08:18 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.005
203.0.113.22 - - [27/Nov/2026:14:08:23 +0300] "GET /api/products/777 HTTP/1.1" 200 2334 "-" "Mozilla/5.0" 0.064
203.0.113.11 - - [27/Nov/2026:14:08:24 +0300] "POST /api/login HTTP/1.1" 200 90 "-" "Mozilla/5.0" 0.199
203.0.113.12 - - [27/Nov/2026:14:08:24 +0300] "GET /api/search?q=cookbook HTTP/1.1" 200 5551 "-" "Mozilla/5.0" 0.151
203.0.113.31 - - [27/Nov/2026:14:08:26 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.087
203.0.113.36 - - [27/Nov/2026:14:08:28 +0300] "GET /api/products/977 HTTP/1.1" 200 1403 "-" "Mozilla/5.0" 0.019
203.0.113.12 - - [27/Nov/2026:14:08:34 +0300] "GET /api/products/907 HTTP/1.1" 200 1836 "-" "Mozilla/5.0" 0.043
203.0.113.33 - - [27/Nov/2026:14:08:34 +0300] "GET /api/search?q=dune HTTP/1.1" 200 6023 "-" "Mozilla/5.0" 2.688
203.0.113.22 - - [27/Nov/2026:14:08:35 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.801
203.0.113.24 - - [27/Nov/2026:14:08:36 +0300] "POST /api/login HTTP/1.1" 200 90 "-" "Mozilla/5.0" 0.144
203.0.113.36 - - [27/Nov/2026:14:08:36 +0300] "GET /api/products/384 HTTP/1.1" 200 1723 "-" "Mozilla/5.0" 0.058
203.0.113.34 - - [27/Nov/2026:14:08:40 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.004
203.0.113.24 - - [27/Nov/2026:14:08:46 +0300] "GET /api/products/415 HTTP/1.1" 200 1154 "-" "Mozilla/5.0" 0.055
203.0.113.37 - - [27/Nov/2026:14:08:46 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.031
203.0.113.35 - - [27/Nov/2026:14:08:53 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.070
203.0.113.26 - - [27/Nov/2026:14:08:54 +0300] "GET /api/products/769 HTTP/1.1" 200 2392 "-" "Mozilla/5.0" 0.057
203.0.113.10 - - [27/Nov/2026:14:09:02 +0300] "GET /api/products/174 HTTP/1.1" 200 1236 "-" "Mozilla/5.0" 0.018
203.0.113.17 - - [27/Nov/2026:14:09:04 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.045
203.0.113.39 - - [27/Nov/2026:14:09:09 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.574
203.0.113.6 - - [27/Nov/2026:14:09:10 +0300] "GET /api/search?q=dune HTTP/1.1" 200 5791 "-" "Mozilla/5.0" 0.190
203.0.113.36 - - [27/Nov/2026:14:09:22 +0300] "GET /api/products/175 HTTP/1.1" 200 1088 "-" "Mozilla/5.0" 0.018
203.0.113.9 - - [27/Nov/2026:14:09:22 +0300] "GET /api/products/795 HTTP/1.1" 200 1231 "-" "Mozilla/5.0" 0.059
203.0.113.28 - - [27/Nov/2026:14:09:25 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.006
203.0.113.20 - - [27/Nov/2026:14:09:26 +0300] "POST /api/checkout HTTP/1.1" 200 640 "-" "Mozilla/5.0" 0.638
203.0.113.19 - - [27/Nov/2026:14:09:28 +0300] "GET /api/search?q=atlas HTTP/1.1" 200 4396 "-" "Mozilla/5.0" 0.095
203.0.113.22 - - [27/Nov/2026:14:09:32 +0300] "GET /api/products/641 HTTP/1.1" 200 951 "-" "Mozilla/5.0" 0.067
203.0.113.27 - - [27/Nov/2026:14:09:35 +0300] "GET /api/search?q=tolkien HTTP/1.1" 200 8687 "-" "Mozilla/5.0" 0.187
203.0.113.35 - - [27/Nov/2026:14:09:40 +0300] "GET /static/app.9f2c41.js HTTP/1.1" 200 182000 "-" "Mozilla/5.0" 0.002
203.0.113.18 - - [27/Nov/2026:14:09:42 +0300] "GET /api/products/916 HTTP/1.1" 200 1637 "-" "Mozilla/5.0" 0.075
203.0.113.34 - - [27/Nov/2026:14:09:42 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.084
203.0.113.32 - - [27/Nov/2026:14:09:56 +0300] "GET /api/products/802 HTTP/1.1" 200 1584 "-" "Mozilla/5.0" 0.069
203.0.113.21 - - [27/Nov/2026:14:09:57 +0300] "GET /api/products/562 HTTP/1.1" 200 1654 "-" "Mozilla/5.0" 0.038
203.0.113.25 - - [27/Nov/2026:14:09:57 +0300] "GET /api/products/820 HTTP/1.1" 200 2126 "-" "Mozilla/5.0" 0.018
203.0.113.25 - - [27/Nov/2026:14:09:57 +0300] "GET /api/search?q=tolkien HTTP/1.1" 200 3846 "-" "Mozilla/5.0" 0.128
203.0.113.24 - - [27/Nov/2026:14:09:59 +0300] "POST /api/cart/items HTTP/1.1" 201 310 "-" "Mozilla/5.0" 0.067
203.0.113.39 - - [27/Nov/2026:14:09:59 +0300] "GET /api/products/110 HTTP/1.1" 200 1692 "-" "Mozilla/5.0" 0.022
FILE:examples/app.jsonl
{"time": "2026-11-27T14:00:10+03:00", "method": "GET", "path": "/api/orders/5000", "status": 200, "duration_ms": 41, "bytes": 820}
{"time": "2026-11-27T14:01:10+03:00", "method": "GET", "path": "/api/orders/5001", "status": 200, "duration_ms": 44, "bytes": 820}
{"time": "2026-11-27T14:02:10+03:00", "method": "GET", "path": "/api/orders/5002", "status": 200, "duration_ms": 47, "bytes": 820}
{"time": "2026-11-27T14:03:10+03:00", "method": "GET", "path": "/api/orders/5003", "status": 200, "duration_ms": 50, "bytes": 820}
{"time": "2026-11-27T14:04:10+03:00", "method": "GET", "path": "/api/orders/5004", "status": 200, "duration_ms": 53, "bytes": 820}
{"time": "2026-11-27T14:05:10+03:00", "method": "GET", "path": "/api/orders/5005", "status": 200, "duration_ms": 56, "bytes": 820}
{"time": "2026-11-27T14:06:30+03:00", "method": "POST", "path": "/api/orders/5006/refund", "status": 500, "duration_ms": 2140, "bytes": 120}
FILE:scripts/access_log.py
#!/usr/bin/env python3
"""access_log.py - find the slow and failing endpoints in an HTTP access log.
Reads Nginx/Apache "combined" lines (optionally followed by a request time in seconds, e.g. Nginx
$request_time, or microseconds via --time-unit us for Apache %D) or JSON lines with method, path, status
and duration_ms. Groups requests by route (query strings dropped, numeric ids, UUIDs and long hex hashes
replaced by :id, :uuid and :hash), computes count, share, 4xx/5xx rates and p50/p90/p95/p99/max latency
per route, finds minutes with 5xx spikes and flags routes that break the latency target or error budget.
Usage:
access_log.py LOG [LOG ...] [--slo-ms 500] [--error-pct 1.0] [--client-error-pct 20] [--min-count 20]
[--time-unit s|ms|us] [--group-by route|path] [--top 15] [--format text|md|csv|json]
access_log.py --self-test
Exit: 0 = no flags, 1 = flags present, 2 = unreadable input or no parsable lines.
Python 3.8+ standard library only. Reads logs only; never sends anything anywhere."""
import argparse, csv, io, json, math, re, sys
from collections import defaultdict
from datetime import datetime
COMBINED = re.compile(
r'^(?P<ip>\S+) \S+ \S+ \[(?P<time>[^\]]+)\] "(?P<method>[A-Z]+) (?P<target>\S+)(?: HTTP/[0-9.]+)?" '
r'(?P<status>\d{3}) (?P<bytes>\d+|-)(?: "(?P<ref>[^"]*)" "(?P<ua>[^"]*)")?(?P<rest>.*)$')
UUID = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
HEX = re.compile(r"^[0-9a-fA-F]{16,}$")
NUM = re.compile(r"^\d+$")
STATIC = (".css", ".js", ".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico", ".woff", ".woff2", ".map", ".webp")
def route_of(target, group_by="route"):
path = target.split("?", 1)[0].split("#", 1)[0] or "/"
if group_by == "path":
return path
out = []
for seg in path.split("/"):
if NUM.match(seg): out.append(":id")
elif UUID.match(seg): out.append(":uuid")
elif HEX.match(seg): out.append(":hash")
else: out.append(seg)
r = "/".join(out)
if r.lower().endswith(STATIC):
r = r.rsplit("/", 1)[0] + "/*" + r[r.rfind("."):].lower()
return r or "/"
def parse_time(s):
for fmt in ("%d/%b/%Y:%H:%M:%S %z", "%Y-%m-%dT%H:%M:%S%z", "%Y-%m-%dT%H:%M:%S.%f%z", "%Y-%m-%d %H:%M:%S"):
try:
return datetime.strptime(s.replace("Z", "+0000"), fmt)
except ValueError:
pass
return None
def parse_line(line, time_unit="s"):
"""Return dict(time, method, target, status, bytes, ms) or None. ms is None when no latency is logged."""
line = line.strip()
if not line:
return None
if line.startswith("{"):
try:
j = json.loads(line)
ms = j.get("duration_ms", j.get("request_time_ms"))
if ms is None and j.get("request_time") is not None:
ms = float(j["request_time"]) * 1000
return {"time": parse_time(str(j.get("time", ""))), "method": str(j["method"]).upper(),
"target": str(j["path"]), "status": int(j["status"]), "bytes": int(j.get("bytes") or 0),
"ms": None if ms is None else float(ms)}
except (ValueError, KeyError, TypeError):
return None
m = COMBINED.match(line)
if not m:
return None
ms = None
rest = (m.group("rest") or "").split()
if rest:
try:
v = float(rest[-1])
ms = v * {"s": 1000.0, "ms": 1.0, "us": 0.001}[time_unit]
except ValueError:
ms = None
b = m.group("bytes")
return {"time": parse_time(m.group("time")), "method": m.group("method"), "target": m.group("target"),
"status": int(m.group("status")), "bytes": 0 if b == "-" else int(b), "ms": ms}
def pct(values, p):
"""Nearest-rank percentile of a sorted list (p in 0-100)."""
if not values:
return None
k = max(1, int(math.ceil(p / 100.0 * len(values))))
return values[k - 1]
def analyze(lines, slo_ms=500.0, error_pct=1.0, client_error_pct=20.0, min_count=20, time_unit="s",
group_by="route", top=15, spike_min_requests=10):
groups = defaultdict(lambda: {"n": 0, "s4": 0, "s5": 0, "ms": [], "bytes": 0})
minutes = defaultdict(lambda: [0, 0])
total = bad = with_ms = 0
slowest = []
for raw in lines:
r = parse_line(raw, time_unit)
if r is None:
if raw.strip():
bad += 1
continue
total += 1
key = r["method"] + " " + route_of(r["target"], group_by)
g = groups[key]
g["n"] += 1; g["bytes"] += r["bytes"]
if 400 <= r["status"] < 500: g["s4"] += 1
if r["status"] >= 500: g["s5"] += 1
if r["ms"] is not None:
g["ms"].append(r["ms"]); with_ms += 1
slowest.append((r["ms"], r["method"], r["target"], r["status"]))
if r["time"] is not None:
mk = r["time"].strftime("%Y-%m-%d %H:%M")
minutes[mk][0] += 1
if r["status"] >= 500: minutes[mk][1] += 1
routes, flags = [], []
all_ms = sorted(x for g in groups.values() for x in g["ms"])
for key, g in groups.items():
v = sorted(g["ms"])
row = {"route": key, "count": g["n"], "share_pct": round(100.0 * g["n"] / total, 1) if total else 0,
"rate_4xx_pct": round(100.0 * g["s4"] / g["n"], 1), "rate_5xx_pct": round(100.0 * g["s5"] / g["n"], 1),
"p50_ms": pct(v, 50), "p90_ms": pct(v, 90), "p95_ms": pct(v, 95), "p99_ms": pct(v, 99),
"max_ms": v[-1] if v else None, "avg_kb": round(g["bytes"] / g["n"] / 1024.0, 1)}
routes.append(row)
if g["n"] < min_count:
continue
if row["p95_ms"] is not None and row["p95_ms"] > slo_ms:
flags.append(("L01", key, "p95 %.0f ms is above the %.0f ms target (%d request(s))" % (row["p95_ms"], slo_ms, g["n"])))
if row["rate_5xx_pct"] >= error_pct:
flags.append(("L02", key, "%.1f%% server errors (%d of %d), budget %.1f%%" % (row["rate_5xx_pct"], g["s5"], g["n"], error_pct)))
if row["rate_4xx_pct"] >= client_error_pct:
flags.append(("L03", key, "%.1f%% client errors (%d of %d): broken links, auth or validation?" % (row["rate_4xx_pct"], g["s4"], g["n"])))
if row["p50_ms"] and row["p99_ms"] is not None and row["p99_ms"] >= 5 * row["p50_ms"] and row["p99_ms"] > slo_ms:
flags.append(("L05", key, "long tail: p99 %.0f ms is %.1fx p50 %.0f ms" % (row["p99_ms"], row["p99_ms"] / row["p50_ms"], row["p50_ms"])))
total5 = sum(g["s5"] for g in groups.values())
base = 100.0 * total5 / total if total else 0
spikes = []
for mk in sorted(minutes):
n, e = minutes[mk]
if n >= spike_min_requests and e and 100.0 * e / n >= max(5.0, 3 * base):
spikes.append({"minute": mk, "requests": n, "errors_5xx": e, "rate_pct": round(100.0 * e / n, 1)})
flags.append(("L04", mk, "5xx spike: %d of %d requests (%.0f%%) vs %.1f%% overall" % (e, n, 100.0 * e / n, base)))
if total and with_ms == 0:
flags.append(("L06", "-", "no request time found in the log: add $request_time (Nginx) or %D (Apache) to see latency"))
if bad:
flags.append(("E01", "-", "%d line(s) could not be parsed" % bad))
order = {"L02": 0, "L04": 1, "L01": 2, "L05": 3, "L03": 4, "L06": 5, "E01": 6}
flags.sort(key=lambda f: (order[f[0]], f[1]))
routes.sort(key=lambda r: (-(r["p95_ms"] or 0), -r["count"]))
slowest.sort(key=lambda x: -x[0])
summary = {"requests": total, "unparsed": bad, "with_latency": with_ms, "routes": len(routes),
"rate_5xx_pct": round(base, 2), "p50_ms": pct(all_ms, 50), "p95_ms": pct(all_ms, 95),
"p99_ms": pct(all_ms, 99), "settings": {"slo_ms": slo_ms, "error_pct": error_pct,
"client_error_pct": client_error_pct, "min_count": min_count, "group_by": group_by}}
return {"summary": summary, "routes": routes[:top] if top else routes, "spikes": spikes,
"slowest": [{"ms": round(s[0], 1), "request": "%s %s" % (s[1], s[2]), "status": s[3]} for s in slowest[:5]],
"flags": [{"code": c, "where": w, "detail": d} for c, w, d in flags]}
def fmt_ms(v):
return "-" if v is None else ("%.0f" % v)
def render(res, form):
s = res["summary"]
if form == "json":
return json.dumps(res, indent=2)
if form == "csv":
buf = io.StringIO(); w = csv.writer(buf)
w.writerow(["route", "count", "share_pct", "rate_4xx_pct", "rate_5xx_pct", "p50_ms", "p90_ms", "p95_ms", "p99_ms", "max_ms"])
for r in res["routes"]:
w.writerow([r["route"], r["count"], r["share_pct"], r["rate_4xx_pct"], r["rate_5xx_pct"]] + [fmt_ms(r[k]) for k in ("p50_ms", "p90_ms", "p95_ms", "p99_ms", "max_ms")])
return buf.getvalue()
md = form == "md"
L = []
head = "Requests %d (%d unparsed) | routes %d | 5xx %.2f%% | p50 %s ms, p95 %s ms, p99 %s ms | target p95 <= %.0f ms" % (
s["requests"], s["unparsed"], s["routes"], s["rate_5xx_pct"], fmt_ms(s["p50_ms"]), fmt_ms(s["p95_ms"]), fmt_ms(s["p99_ms"]), s["settings"]["slo_ms"])
L.append(("## Access log summary\n\n" if md else "") + head)
L.append("")
if md:
L += ["| Route | Count | Share | 4xx | 5xx | p50 | p95 | p99 | max |", "|---|---|---|---|---|---|---|---|---|"]
for r in res["routes"]:
L.append("| `%s` | %d | %.1f%% | %.1f%% | %.1f%% | %s | %s | %s | %s |" % (r["route"], r["count"], r["share_pct"], r["rate_4xx_pct"], r["rate_5xx_pct"], fmt_ms(r["p50_ms"]), fmt_ms(r["p95_ms"]), fmt_ms(r["p99_ms"]), fmt_ms(r["max_ms"])))
else:
L.append("%-34s %6s %6s %6s %6s %6s %6s %6s %7s" % ("ROUTE", "COUNT", "SHARE", "4XX%", "5XX%", "P50", "P95", "P99", "MAX"))
for r in res["routes"]:
L.append("%-34s %6d %5.1f%% %6.1f %6.1f %6s %6s %6s %7s" % (r["route"][:34], r["count"], r["share_pct"], r["rate_4xx_pct"], r["rate_5xx_pct"], fmt_ms(r["p50_ms"]), fmt_ms(r["p95_ms"]), fmt_ms(r["p99_ms"]), fmt_ms(r["max_ms"])))
L.append("")
L.append(("### Flags" if md else "FLAGS") + " (%d)" % len(res["flags"]))
for f in res["flags"]:
L.append(("- **%s** `%s`: %s" if md else "%s %s %s") % (f["code"], f["where"], f["detail"]))
if not res["flags"]:
L.append("none")
if res["slowest"]:
L.append("")
L.append("### Slowest requests" if md else "SLOWEST REQUESTS")
for x in res["slowest"]:
L.append(("- %s ms `%s` (%d)" if md else "%8s ms %s (%d)") % (fmt_ms(x["ms"]), x["request"], x["status"]))
return "\n".join(L) + "\n"
def self_test():
ok = [0, 0]
def check(name, cond):
ok[0] += 1; ok[1] += bool(cond)
print(("PASS " if cond else "FAIL ") + name)
L1 = '203.0.113.9 - - [28/Nov/2026:10:00:01 +0300] "GET /api/orders/123?page=2 HTTP/1.1" 200 512 "-" "curl/8" 0.084'
r = parse_line(L1)
check("combined line with request_time parsed", r and r["status"] == 200 and abs(r["ms"] - 84.0) < 1e-6 and r["method"] == "GET")
check("Apache %D microseconds", abs(parse_line(L1.rsplit(" ", 1)[0] + " 84000", "us")["ms"] - 84.0) < 1e-6)
r2 = parse_line('203.0.113.9 - - [28/Nov/2026:10:00:01 +0300] "GET / HTTP/1.1" 304 - "-" "x"')
check("no latency field -> ms None, bytes '-' -> 0", r2 and r2["ms"] is None and r2["bytes"] == 0)
check("common format without referer/agent", parse_line('10.0.0.1 - - [28/Nov/2026:10:00:01 +0300] "POST /login HTTP/1.1" 401 12')["status"] == 401)
j = parse_line('{"time":"2026-11-28T10:00:02+03:00","method":"post","path":"/api/pay","status":502,"duration_ms":1200}')
check("JSON line parsed", j and j["method"] == "POST" and j["status"] == 502 and j["ms"] == 1200.0)
check("garbage -> None", parse_line("hello world") is None and parse_line('{"broken": ') is None)
check("route: numeric id", route_of("/api/orders/123?x=1") == "/api/orders/:id")
check("route: uuid and hash", route_of("/u/3f2b8c1e-1d2a-4b3c-9d8e-112233445566/f/a1b2c3d4e5f6a7b8c9d0") == "/u/:uuid/f/:hash")
check("route: static grouped", route_of("/static/app.3f9a.JS") == "/static/*.js")
check("route: --group-by path keeps ids", route_of("/api/orders/123?x=1", "path") == "/api/orders/123")
check("nearest-rank percentiles", pct([10, 20, 30, 40, 50, 60, 70, 80, 90, 100], 95) == 100 and pct(list(range(1, 101)), 50) == 50 and pct([], 50) is None)
def ln(path, st, sec, mm="00", ss="01", method="GET"):
return '198.51.100.7 - - [28/Nov/2026:10:%s:%s +0300] "%s %s HTTP/1.1" %d 100 "-" "t" %.3f' % (mm, ss, method, path, st, sec)
lines = [ln("/api/fast/%d" % i, 200, 0.05) for i in range(40)]
lines += [ln("/api/slow", 200, 0.9 if i % 5 == 0 else 0.2) for i in range(30)]
lines += [ln("/api/pay", 500 if i < 3 else 200, 0.1, mm="05") for i in range(25)]
lines += [ln("/admin", 403, 0.01) for i in range(25)]
lines += ["not a log line"]
res = analyze(lines, min_count=20)
codes = {(f["code"], f["where"]) for f in res["flags"]}
check("fast route grouped into one row", any(r["route"] == "GET /api/fast/:id" and r["count"] == 40 for r in res["routes"]))
check("L01 slow route p95 over target", ("L01", "GET /api/slow") in codes)
check("no L01 for fast route", ("L01", "GET /api/fast/:id") not in codes)
check("L02 5xx over budget", ("L02", "GET /api/pay") in codes)
check("L03 client errors on /admin", ("L03", "GET /admin") in codes)
check("L04 spike minute found", ("L04", "2026-11-28 10:05") in codes)
check("E01 unparsed line counted", res["summary"]["unparsed"] == 1 and any(f["code"] == "E01" for f in res["flags"]))
check("L02 sorted before L01", [f["code"] for f in res["flags"]].index("L02") < [f["code"] for f in res["flags"]].index("L01"))
tail = [ln("/api/search", 200, 0.05) for _ in range(95)] + [ln("/api/search", 200, 2.0) for _ in range(5)]
tc = {f["code"] for f in analyze(tail)["flags"]}
check("L05 long tail (p99 >> p50) without L01", "L05" in tc and "L01" not in tc)
few = analyze([ln("/rare", 500, 3.0) for _ in range(5)], min_count=20)
check("min-count suppresses route flags", not [f for f in few["flags"] if f["code"] in ("L01", "L02", "L05")])
nolat = analyze(['10.0.0.1 - - [28/Nov/2026:10:00:01 +0300] "GET / HTTP/1.1" 200 5 "-" "x"'] * 3)
check("L06 when no latency is logged", any(f["code"] == "L06" for f in nolat["flags"]))
check("json render parses", json.loads(render(res, "json"))["summary"]["requests"] == 120)
check("csv render header", render(res, "csv").splitlines()[0].startswith("route,count"))
check("md render has table", "| Route | Count" in render(res, "md"))
clean = analyze([ln("/ok", 200, 0.03) for _ in range(50)])
check("clean log: no flags", clean["flags"] == [])
print("%d/%d checks passed" % (ok[1], ok[0]))
return 0 if ok[0] == ok[1] else 1
def main(argv=None):
a = argparse.ArgumentParser(description="Find slow and failing endpoints in HTTP access logs.")
a.add_argument("logs", nargs="*")
a.add_argument("--slo-ms", type=float, default=500.0, help="p95 latency target per route (default 500)")
a.add_argument("--error-pct", type=float, default=1.0, help="5xx budget per route in percent (default 1.0)")
a.add_argument("--client-error-pct", type=float, default=20.0, help="4xx share that is flagged (default 20)")
a.add_argument("--min-count", type=int, default=20, help="ignore routes with fewer requests (default 20)")
a.add_argument("--time-unit", choices=["s", "ms", "us"], default="s", help="unit of the trailing request time")
a.add_argument("--group-by", choices=["route", "path"], default="route")
a.add_argument("--top", type=int, default=15, help="routes to list, 0 = all")
a.add_argument("--format", choices=["text", "md", "csv", "json"], default="text")
a.add_argument("--self-test", action="store_true")
o = a.parse_args(argv)
if o.self_test:
return self_test()
if not o.logs:
a.print_usage(sys.stderr); return 2
lines = []
for p in o.logs:
try:
with open(p, encoding="utf-8", errors="replace") as fh:
lines += fh.readlines()
except OSError as e:
print("error: cannot read %s: %s" % (p, e), file=sys.stderr); return 2
res = analyze(lines, o.slo_ms, o.error_pct, o.client_error_pct, o.min_count, o.time_unit, o.group_by, o.top)
if res["summary"]["requests"] == 0:
print("error: no parsable log lines (check the format; see references/log-formats.md)", file=sys.stderr); return 2
sys.stdout.write(render(res, o.format))
return 1 if res["flags"] else 0
if __name__ == "__main__":
sys.exit(main())
Finds what makes a Git repository big and slow to clone: large files in HEAD and in history, deleted files still stored, binaries with many versions, committed node_modules or build output and credential-like files. Suggests .gitignore, Git LFS and safe history cleanup steps. Stdlib Python.
---
name: git-repository-large-file-and-bloat-finder
description: Finds what makes a Git repository big and slow to clone: large files in HEAD and in history, deleted files still stored, binaries with many versions, committed node_modules or build output and credential-like files. Suggests .gitignore, Git LFS and safe history cleanup steps. Stdlib Python.
---
# Git Repository Large File and Bloat Finder
You help developers and tech leads understand why a Git repository is big, why clones and CI checkouts are slow, and what to do about it without breaking anyone's work. A 2 GB repository is rarely 2 GB of source code: it is usually one forgotten video, a database dump deleted years ago, a design file with 40 versions or a committed `node_modules`. You find those objects, explain the cost and propose the smallest safe fix.
You never rewrite history or delete anything yourself. History rewrites affect every clone, fork and open pull request, so you present them as a plan for the team to approve, with a backup and a communication step.
## Files in this skill
- `scripts/repo_bloat.py` - reads all objects reachable from all refs (`git rev-list --objects --all` + `git cat-file --batch-check`), groups blobs by path, flags B01-B05, lists top paths and extensions, and prints .gitignore, Git LFS and `git filter-repo` suggestions; `--format text|md|json`; `--objects-file`/`--head-file` for offline listings; `--self-test` runs 20 checks including a real temporary repository (Python 3.8+ standard library and the git CLI)
- `references/bloat-causes.md` - the usual causes, how to recognize each one and how much it costs
- `references/cleanup-playbook.md` - fixes from least to most disruptive: ignore and untrack, Git LFS, shallow and partial clones, history rewrite, secret rotation
- `templates/repo-bloat-report.md` - a short report and decision template for the team
- `examples/objects.txt` + `examples/head.txt` - a captured listing of a fictional web app repository
## Workflow
### 1. Measure first
Ask for the repository path (or run in the current checkout) and check the basics:
```
git count-objects -vH
du -sh .git
git rev-list --count --all
```
Ask how the repository is hosted (GitHub, GitLab, Bitbucket, self-hosted), whether forks exist, how many people and CI pipelines clone it, and whether Git LFS is already in use.
### 2. Run the scan
```
python3 scripts/repo_bloat.py --repo /path/to/repo
python3 scripts/repo_bloat.py --repo . --threshold-mb 2 --top 25
python3 scripts/repo_bloat.py --repo . --format md > repo-bloat.md
python3 scripts/repo_bloat.py --repo . --format json
python3 scripts/repo_bloat.py --objects-file objects.txt --head-file head.txt
python3 scripts/repo_bloat.py --self-test
```
For a repository you cannot run the script in, capture the listings there and scan them offline:
```
git rev-list --objects --all | git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(objectsize:disk) %(rest)' > objects.txt
git ls-tree -r --name-only HEAD > head.txt
```
Exit code 0 = no findings, 1 = findings, 2 = not a repository or unreadable input.
| Code | Meaning |
|---|---|
| B01 | large file only in history (deleted from HEAD), or many versions of a deleted file adding up above the threshold |
| B02 | large file still in HEAD (every clone and checkout downloads it) |
| B03 | binary file with 3 or more versions; each change stores a full new copy |
| B04 | generated or vendored folder or file type committed (node_modules, dist, build, vendor, venv, logs, compiled files) |
| B05 | credential-like file in history (.env, private keys, keystores, credentials JSON) |
### 3. Interpret
- Compare `history_only_bytes` with the pack size: if most of the weight is only in history, a rewrite is the only way to shrink clones; if it is in HEAD, ignoring and LFS help right away.
- Sizes are uncompressed blob sizes; text compresses well in packs, binaries do not. `objectsize:disk` in the JSON output shows what the pack really stores.
- B05 is a security finding first and a size finding second. Treat any secret found as leaked.
- A large file in HEAD that the product needs (a test fixture, a font) may be fine; ask before suggesting removal.
### 4. Choose the fix
Use `references/cleanup-playbook.md` and pick the least disruptive fix that solves the problem:
1. Stop the growth: `.gitignore`, `git rm -r --cached`, a pre-commit or CI size check.
2. Move binaries that must stay versioned to Git LFS (new versions right away; old versions only with `git lfs migrate`).
3. Make clones cheaper without rewriting: `--filter=blob:none` partial clones, shallow CI checkouts, sparse checkout.
4. Rewrite history only with team agreement: freeze merges, back up a mirror, run `git filter-repo`, force-push, ask everyone to re-clone, ask the host to run garbage collection.
5. For B05: rotate the credential first, then clean history, then check forks and CI caches.
### 5. Report
Fill `templates/repo-bloat-report.md`: current size and clone time, top findings, the recommended fix with its impact on the team, the steps, and how you will keep the repository small.
## Example
```
python3 scripts/repo_bloat.py --objects-file examples/objects.txt --head-file examples/head.txt
```
Result: 59 unique blobs, 132.6 MB uncompressed, 79.2 MB of it only in history. Two credential-like files (`config/.env`, `deploy/staging.pem`) are flagged first; a deleted 48 MB hero video, a 12 MB SQLite dev database and a customer CSV export sit only in history; `logo.psd` has 4 versions (29.8 MB); `frontend/dist/`, `frontend/node_modules/` and `*.log` were committed. Suggestions: ignore and untrack the generated paths, LFS for `*.psd` and `*.png`, rotate the secrets, then a coordinated `git filter-repo` rewrite.
## Limits
- The scan reads only objects reachable from local refs; fetch all branches and tags first (`git fetch --all --tags`) or results will be incomplete. Reflog-only and unreachable objects are ignored.
- Folder and extension rules are heuristics: a `build/` folder may be real source in some projects. Confirm before ignoring.
- Credential detection is by file name only; secrets inside ordinary files need a dedicated secret scanner.
- The script never changes the repository; every command it prints must be reviewed and run by a person.
FILE:references/bloat-causes.md
# Common causes of repository bloat
| Cause | How to recognize it | Why it hurts | Typical fix |
|---|---|---|---|
| Media and design files (mp4, mov, psd, sketch, fig exports) | B02/B03 on `assets/`, `design/`, `marketing/` | Binaries barely compress and every edit stores a full copy | Git LFS or an asset store (S3, a DAM, the design tool itself) |
| Deleted large files | B01, `history only` in the top paths | Every clone still downloads them, forever | History rewrite with `git filter-repo --invert-paths` |
| Database dumps and SQLite dev databases | `.sql`, `.sqlite`, `.db`, `.dump` in B01/B02 | Large, often contain real personal data | Remove, rotate if they contain secrets, regenerate from seed scripts |
| Data exports (CSV, JSON, Parquet) | `data/`, `exports/`, many versions of one file | Grows with every refresh, may contain customer data | Keep in object storage; commit a small sample instead |
| Dependency folders | B04 on `node_modules/`, `vendor/`, `.venv/`, `Pods/` | Thousands of files, slow checkouts, noisy diffs | `.gitignore` + lock files; vendoring only when policy requires it |
| Build output | B04 on `dist/`, `build/`, `target/`, `bin/`, `*.map` | Regenerated on every build, conflicts in every merge | Build in CI, publish artifacts to a registry or release page |
| Logs and caches | B04 on `*.log`, `*.tmp`, `__pycache__/` | Grow without limit, may leak tokens and user data | `.gitignore`, clean the working tree |
| Compiled binaries and installers | `.exe`, `.dll`, `.so`, `.jar`, `.apk`, `.dmg` | Large and change with every release | Release assets or a package registry |
| Credentials | B05 on `.env`, `*.pem`, `id_rsa`, `credentials.json` | A security incident, regardless of size | Rotate first, then remove from history |
## Rough cost model
- Clone size: approximately the pack size (`git count-objects -vH`, `size-pack`). Every developer and every CI job without a cache pays it.
- Checkout size: the files in HEAD. Large HEAD files slow every branch switch and Docker build context.
- History-only weight: costs bandwidth and disk on every full clone but nothing on checkout. Only a rewrite removes it.
- Time: at 50 Mbit/s, 1 GB takes about 3 minutes to clone; multiply by CI runs per day to show the team the real cost.
## Questions to ask before acting
1. Is any of this needed to build or test the product? Who owns it?
2. Does the file contain personal or customer data? (Then removal is a privacy task, not just cleanup.)
3. How many forks, mirrors and open pull requests exist? (A rewrite invalidates them.)
4. Is Git LFS available on the host and paid for (storage and bandwidth quotas)?
FILE:references/cleanup-playbook.md
# Cleanup playbook (least to most disruptive)
Always start at the top and stop as soon as the problem is solved.
## 1. Stop the growth (no history change)
```
echo "frontend/node_modules/" >> .gitignore
echo "frontend/dist/" >> .gitignore
echo "*.log" >> .gitignore
git rm -r --cached frontend/node_modules frontend/dist logs/worker.log
git commit -m "Stop tracking generated files"
```
Add a guard so it does not happen again, for example a CI step that fails when a new file is over 5 MB:
```
git diff --name-only --diff-filter=AM origin/main...HEAD | while read -r f; do if [ -f "$f" ] && [ "$(wc -c < "$f")" -gt 5242880 ]; then echo "too large: $f"; exit 1; fi; done
```
Many hosts also offer push rules or file size limits; turn them on.
## 2. Git LFS for binaries that must stay versioned
```
git lfs install
git lfs track "*.psd" "*.png"
git add .gitattributes
git commit -m "Track design files with Git LFS"
```
This only affects new commits. To move old versions too, `git lfs migrate import --include="*.psd,*.png" --everything` rewrites history (see step 4 for the coordination rules). Check the host's LFS storage and bandwidth quotas first.
## 3. Cheaper clones without rewriting
- Partial clone: `git clone --filter=blob:none <url>` downloads file contents only when needed.
- CI: shallow fetch (`fetch-depth: 1` or `git fetch --depth 1`) and cache the repository between jobs.
- Sparse checkout for monorepos: `git sparse-checkout set services/api`.
These help immediately and need no team coordination.
## 4. History rewrite (team decision)
Use `git filter-repo` (install with `pip install git-filter-repo`); avoid the old `git filter-branch`.
1. Announce a freeze window; ask everyone to push or park their work.
2. Back up: `git clone --mirror <url> backup.git`.
3. Rewrite in a fresh mirror clone:
```
git clone --mirror <url> repo.git && cd repo.git
git filter-repo --invert-paths --path 'assets/brand/hero-video.mp4' --path 'db/dev.sqlite' --path 'frontend/node_modules/'
```
Or by size: `git filter-repo --strip-blobs-bigger-than 10M`.
4. Check the result (`git count-objects -vH`, run the scan again, build the project).
5. Force-push all refs (`git push --force --mirror`), with branch protection temporarily adjusted.
6. Everyone re-clones; old clones must not be pushed again or the objects come back.
7. Ask the host to run garbage collection; cached views, forks and pull request refs may keep the old objects until then.
## 5. Leaked credentials (B05)
1. Rotate or revoke the credential immediately: assume it is compromised.
2. Check access logs for its use.
3. Remove the file from history (step 4) and add the pattern to `.gitignore`.
4. Check forks, CI caches, artifacts and backups; a rewrite does not reach them.
5. Add a secret scanner to pre-commit and CI.
FILE:templates/repo-bloat-report.md
# Repository bloat report: {{repo_name}}
Date: {{date}} | Prepared by: {{author}} | Scan threshold: {{threshold}}
## Current state
- Pack size: {{pack_size}} | Files in HEAD: {{head_files}} | Commits: {{commit_count}}
- Full clone time on a typical connection: {{clone_time}} | CI clones per day: {{ci_clones}}
- Weight only in history: {{history_only}} ({{history_share}} of the total)
## Top findings
| Code | Path | Size | Why it matters |
|---|---|---|---|
| {{code}} | {{path}} | {{size}} | {{impact}} |
## Security first
- Credential-like files found: {{secrets_found}}
- Rotation status: {{rotation_status}} (owner: {{owner}})
## Recommended fix
- Option chosen: {{option}} (stop growth / LFS / cheaper clones / history rewrite)
- Expected result: {{expected_size}} pack, {{expected_clone_time}} clone time
- Impact on the team: {{team_impact}} (freeze window, re-clone, open pull requests)
## Steps
1. {{step_1}}
2. {{step_2}}
3. {{step_3}}
## Keeping it small
- Guard: {{guard}} (size check in CI, push rules, pre-commit hook)
- Review again on: {{next_review_date}}
FILE:examples/objects.txt
blob 987a907e4523b6111c4032a2de469e80d6318a67 6144 2048 README.md
blob 467a9a30da173bcb871b88c24a02f60c24e7f9f9 6444 2048 README.md
blob 8ef230704ac1b68adc2b5748df15968e4ddb3088 6744 2048 README.md
blob 656d9098a0fc0df4bdd052ef009a292ff8c52848 7044 2048 README.md
blob 3a92412f2e656df43d5eb4459ac6c6b2302b6b8e 7344 2048 README.md
blob 339b73b1021ec2d5a0d68df3ed3d6b1a531293e0 14336 4096 src/app/main.py
blob ca58bbbda0df031c4994e89dc0407ed538c0aad0 14836 4096 src/app/main.py
blob fdfc0acc5dc7fd2c7b21fe76f704a67a6794af52 15336 4096 src/app/main.py
blob c5f063b21bb5ccdc0f244717285e3b3aa0126eae 15836 4096 src/app/main.py
blob 68c156c282e4dbb74fce3d1c4c93f96ef8ae18f4 16336 4096 src/app/main.py
blob 3dafece57cdeb9b9f322889d15e2a29fb6b72d40 16836 4096 src/app/main.py
blob c7d29b6a0f4e7e4db03f1857834c0e724c914995 17336 4096 src/app/main.py
blob 13ff860496311c12569e38b3a9f73cfb25fbf46f 17836 4096 src/app/main.py
blob eb5b0bd6b49ca65809fabb47c8710d867c8298d4 18336 4096 src/app/main.py
blob 5e51b6d4ddb5bc57b05980620b6fb3b51df53c0d 18836 4096 src/app/main.py
blob 8ca5b647d515af133295911f40fb50b449463cc8 19336 4096 src/app/main.py
blob 7ec4c4ea18e09a533575193190c997f2cc3d4d36 19836 4096 src/app/main.py
blob b8cc9ba2bc56eb1d4dc005c4533494fd223b047f 22528 6144 src/app/billing.py
blob 2e09d8b2e9f72e141f1ae13130739ab1a69d0254 22928 6144 src/app/billing.py
blob 1229e1c043d923b8bb18544347d15f896f0655c2 23328 6144 src/app/billing.py
blob 84357f16b451644e27fc070e3ecf8412a28ebd84 23728 6144 src/app/billing.py
blob 67bc2edb1d10df2d4c09e9ef447d1009beea03f2 24128 6144 src/app/billing.py
blob e603f31f8fa50bcde4ece184771d79a3eabb7695 24528 6144 src/app/billing.py
blob 4ab2814bbce6171176ef2cb01067896be3101ac4 24928 6144 src/app/billing.py
blob a494b3e4a3d1d2bf92cd586825fa99a1193c6158 25328 6144 src/app/billing.py
blob 60a7975811a5d84956eff0acc905b1ef7f8fbcdc 5120 2048 src/app/templates/base.html
blob 8b505d827b0d4d726b603881577af4e80a052d51 5220 2048 src/app/templates/base.html
blob 287e546d9d361cabb13e364beb39ef9b1ac7ce69 5320 2048 src/app/templates/base.html
blob 55a0f95169753b93cabc770ef0ffaae3c8ddeabd 5420 2048 src/app/templates/base.html
blob 2ad6207e009687438942e26b7ebf103fef22a6ff 50331648 48821698 assets/brand/hero-video.mp4
blob 3a225ebac43b538c5ea7beabc046812f65af67b5 7340032 7119831 assets/brand/logo.psd
blob 9c5b0b132d594a764230d13ff70f48330ffb370f 7647232 7417815 assets/brand/logo.psd
blob 84736e8dd8c132cee548c2bec98dc5dc5ba176e2 7954432 7715799 assets/brand/logo.psd
blob 069d6d0ff43d270b6bef99fdf0fc0a3f2112a989 8261632 8013783 assets/brand/logo.psd
blob 18d782987a0fa858e2cba05c633902df49991e8c 921600 893952 assets/screens/onboarding.png
blob 410d6195accb75a817fa6149ba8d7f6358b6893c 962560 933683 assets/screens/onboarding.png
blob b5ea2d3014d635d26a33c10a2205b2e8f3b891f5 1003520 973414 assets/screens/onboarding.png
blob f70530d27121cf6025aba939715c1edf0577f83a 3145728 943718 data/customers_export.csv
blob b40ca9568e642ad4030927d94455ed9764aa0055 3350528 943718 data/customers_export.csv
blob 19cf653daa39079239aee328d5ea7ed2bb3cced2 3555328 943718 data/customers_export.csv
blob 2f7f18e1841133120d5cc15925b74484cd383c6c 12582912 2621440 db/dev.sqlite
blob ca143f39bfc924e872c6d2b395225ac5231f74ff 552960 143360 frontend/node_modules/lodash/lodash.js
blob c309ad74f9fc468d6c51acc51ddf31a6dab8b930 1126400 266240 frontend/node_modules/react-dom/cjs/react-dom.development.js
blob fc7ba143307cde940ab1c1bf3e605ee8f83ef771 8388608 1677721 frontend/node_modules/typescript/lib/typescript.js
blob 965fe4a622f24b31a613a9b352c36e02a15e304c 2097152 614400 frontend/dist/app.bundle.js
blob ec9c755c04059eab6161788223042b4d5a89c5d8 2127872 614400 frontend/dist/app.bundle.js
blob 22f555d29e65fa59336b516fb82449944331fa29 2158592 614400 frontend/dist/app.bundle.js
blob 402418e8073e751e4ec5b210bc7c990651e8c466 2189312 614400 frontend/dist/app.bundle.js
blob 5627dea439be9b76645cd085f048255a04f53bcf 2220032 614400 frontend/dist/app.bundle.js
blob e4b799492f2dbeb24371d9d9c5fbf1f7c7d5f80f 2250752 614400 frontend/dist/app.bundle.js
blob 99d4fbc1f35947bddfb1a5956b3f43515e609f87 4194304 629145 logs/worker.log
blob ac63ac9926a59aca550a097616450bfd88419ae1 4194304 629145 logs/worker.log
blob 3649ca8d0a6d4fc4a3a489ae127f2f57f6c12ff5 900 600 config/.env
blob b5dbab6eeda4ceb03e77ea8715beadb595399269 900 600 config/.env
blob 3f8a4ec013300145a11a3eb276114177e5d84481 700 500 config/.env.example
blob e370702e8693d488e1e1ba4284ffdd3af0d8dff7 3072 3072 deploy/staging.pem
blob 2396abc88761182884eac3687470e339883c801a 9216 3072 docs/architecture.md
blob 53d19b2eda8ff06e94c0b7fa90b5f056bb4e54fc 9716 3072 docs/architecture.md
blob 84008c60e233c95a554251fc59a44b90b0f4f693 10216 3072 docs/architecture.md
FILE:examples/head.txt
README.md
src/app/main.py
src/app/billing.py
src/app/templates/base.html
assets/brand/logo.psd
assets/screens/onboarding.png
frontend/dist/app.bundle.js
config/.env.example
docs/architecture.md
logs/worker.log
FILE:scripts/repo_bloat.py
#!/usr/bin/env python3
"""repo_bloat.py - find what makes a Git repository big and slow to clone.
Reads every object reachable from all refs (git rev-list --objects --all + git cat-file --batch-check),
groups blobs by path and flags large files, files deleted from HEAD but still in history, binaries with
many versions, generated/vendored folders and credential-like files. Suggests .gitignore, Git LFS
patterns and history-rewrite commands, but never changes the repository.
Usage:
repo_bloat.py [--repo PATH] [--threshold-mb 5] [--top 15] [--format text|md|json]
repo_bloat.py --objects-file objects.txt --head-file head.txt (offline: pre-captured listings)
repo_bloat.py --self-test
Exit: 0 = no findings, 1 = findings, 2 = not a git repository / unreadable input.
Python 3.8+ standard library only (needs the git CLI unless --objects-file is used)."""
import argparse, json, os, subprocess, sys, tempfile, shutil
from collections import defaultdict
BINARY_EXT = {".zip", ".tar", ".gz", ".tgz", ".7z", ".rar", ".jar", ".war", ".exe", ".dll", ".so", ".dylib",
".iso", ".dmg", ".pkg", ".apk", ".ipa", ".mp4", ".mov", ".avi", ".mkv", ".mp3", ".wav", ".flac",
".psd", ".ai", ".sketch", ".fig", ".blend", ".fbx", ".obj", ".png", ".jpg", ".jpeg", ".gif",
".tif", ".tiff", ".bmp", ".webp", ".pdf", ".sqlite", ".db", ".parquet", ".h5", ".pkl", ".pt",
".onnx", ".bin", ".npy", ".xlsx", ".docx", ".pptx", ".ttf", ".otf", ".woff", ".woff2"}
GENERATED_DIRS = ("node_modules/", "vendor/", "dist/", "build/", "target/", "out/", ".venv/", "venv/",
"__pycache__/", ".next/", "coverage/", "bin/Debug/", "bin/Release/", "obj/")
GENERATED_EXT = {".log", ".tmp", ".cache", ".pyc", ".class", ".o", ".map"}
SECRET_NAMES = {".env", "id_rsa", "id_dsa", "id_ecdsa", "id_ed25519", "credentials.json", "service-account.json",
".npmrc", ".pypirc", ".netrc", "secrets.yml", "secrets.yaml"}
SECRET_EXT = {".pem", ".key", ".p12", ".pfx", ".keystore", ".jks"}
def human(n):
for u in ("B", "KB", "MB", "GB"):
if n < 1024 or u == "GB":
return ("%d %s" % (n, u)) if u == "B" else ("%.1f %s" % (n, u))
n /= 1024.0
def ext_of(path):
base = path.rsplit("/", 1)[-1].lower()
return os.path.splitext(base)[1], base
def generated_key(path):
"""Return the folder (e.g. 'web/node_modules/') or '*.ext' group for generated/vendored paths, else None."""
ext, base = ext_of(path)
for d in GENERATED_DIRS:
idx = ("/" + path).find("/" + d)
if idx >= 0:
return path[:idx + len(d) - 1] + "/"
return ("*" + ext) if ext in GENERATED_EXT else None
def git(repo, *args, stdin=None):
r = subprocess.run(["git", "-C", repo] + list(args), input=stdin, capture_output=True, text=True)
if r.returncode != 0:
raise RuntimeError(r.stderr.strip() or "git failed")
return r.stdout
def read_objects_from_repo(repo):
"""Return (objects, head_paths, pack_bytes). objects = list of (sha, size, disk_size, path)."""
revs = git(repo, "rev-list", "--objects", "--all")
batch = git(repo, "cat-file", "--batch-check=%(objecttype) %(objectname) %(objectsize) %(objectsize:disk) %(rest)", stdin=revs)
objs = parse_objects(batch)
try:
head = set(x for x in git(repo, "ls-tree", "-r", "--name-only", "HEAD").splitlines() if x)
except RuntimeError:
head = set()
pack = 0
for line in git(repo, "count-objects", "-v").splitlines():
k, _, v = line.partition(":")
if k.strip() in ("size", "size-pack"):
pack += int(v.strip() or 0) * 1024
return objs, head, pack
def parse_objects(text):
"""Parse 'type sha size disk path' lines; keep blobs with a path. Paths may contain spaces."""
out = []
for line in text.splitlines():
parts = line.split(" ", 4)
if len(parts) < 5 or parts[0] != "blob" or not parts[4]:
continue
try:
out.append((parts[1], int(parts[2]), int(parts[3]), parts[4]))
except ValueError:
continue
return out
def analyze(objs, head, threshold, pack_bytes=0, top=15):
by_path = defaultdict(lambda: {"versions": 0, "total": 0, "disk": 0, "max": 0, "shas": set()})
seen = set()
for sha, size, disk, path in objs:
p = by_path[path]
if sha in p["shas"]:
continue
p["shas"].add(sha); p["versions"] += 1; p["total"] += size; p["max"] = max(p["max"], size)
if sha not in seen:
p["disk"] += disk
seen.add(sha)
findings = []
def add(code, path, msg, size):
findings.append({"code": code, "path": path, "size": size, "message": msg})
for path, p in by_path.items():
ext, base = ext_of(path)
in_head = path in head
if generated_key(path):
continue # reported once per folder/extension as B04
if p["max"] >= threshold:
add("B02" if in_head else "B01", path, ("large file in HEAD, largest version %s" if in_head else
"large file only in history (deleted from HEAD), largest version %s") % human(p["max"]), p["max"])
elif not in_head and p["total"] >= threshold:
add("B01", path, "deleted from HEAD but %d versions still cost %s in history" % (p["versions"], human(p["total"])), p["total"])
if p["versions"] >= 3 and p["total"] >= threshold / 2 and ext in BINARY_EXT:
add("B03", path, "binary with %d versions, %s in total (each change stores a full copy)" % (p["versions"], human(p["total"])), p["total"])
gen = defaultdict(lambda: [0, 0, 0])
for path, p in by_path.items():
key = generated_key(path)
if key:
gen[key][0] += 1; gen[key][1] += p["total"]; gen[key][2] += path in head
for key, (n, total, nhead) in gen.items():
add("B04", key, "generated or vendored files committed: %d path%s, %s, %s" % (n, "" if n == 1 else "s", human(total),
("%d still in HEAD" % nhead) if nhead else "history only"), total)
for path, p in by_path.items():
ext, base = ext_of(path)
if base in SECRET_NAMES or ext in SECRET_EXT or (base.startswith(".env.") and not base.endswith((".example", ".sample", ".template"))):
add("B05", path, "credential-like file in history%s: treat the secret as leaked and rotate it" % (" and HEAD" if path in head else ""), p["total"])
order = {"B05": 0, "B01": 1, "B02": 2, "B03": 3, "B04": 4}
findings.sort(key=lambda f: (order[f["code"]], -f["size"], f["path"]))
total_blob = sum(p["total"] for p in by_path.values())
head_bytes = sum(p["max"] for k, p in by_path.items() if k in head)
history_only = sum(p["total"] for k, p in by_path.items() if k not in head)
tops = sorted(by_path.items(), key=lambda kv: -kv[1]["total"])[:top]
ext_totals = defaultdict(int)
for path, p in by_path.items():
ext_totals[ext_of(path)[0] or "(none)"] += p["total"]
return {
"summary": {"paths": len(by_path), "unique_blobs": len(seen), "blob_bytes": total_blob,
"history_only_bytes": history_only, "head_paths": len(head), "pack_bytes": pack_bytes,
"threshold_bytes": threshold, "approx_head_bytes": head_bytes},
"top_paths": [{"path": k, "versions": v["versions"], "total": v["total"], "largest": v["max"], "disk": v["disk"], "in_head": k in head} for k, v in tops],
"top_extensions": sorted(([e, n] for e, n in ext_totals.items()), key=lambda x: -x[1])[:8],
"findings": findings,
"suggestions": suggestions(findings),
}
def suggestions(findings):
s, lfs, ignore, purge = [], set(), set(), []
for f in findings:
ext, base = ext_of(f["path"])
if f["code"] in ("B02", "B03") and ext in BINARY_EXT:
lfs.add("*" + ext)
if f["code"] == "B04":
ignore.add(f["path"])
if f["path"].endswith("/"):
purge.append(f["path"])
if f["code"] in ("B01", "B05"):
purge.append(f["path"])
if ignore:
s.append(".gitignore: add " + ", ".join(sorted(ignore)) + " and remove them from the index with: git rm -r --cached <path>")
if lfs:
s.append("Git LFS for new versions: git lfs track " + " ".join('"%s"' % x for x in sorted(lfs)) + " (old versions stay in history unless migrated: git lfs migrate import --include=\"" + ",".join(sorted(lfs)) + "\" --everything)")
if purge:
s.append("History rewrite (coordinate with the team, back up first, every clone must re-clone): git filter-repo --invert-paths " + " ".join("--path '%s'" % p for p in sorted(set(purge))[:10]))
if any(f["code"] == "B05" for f in findings):
s.append("Secrets: rotate every credential found BEFORE rewriting history; a rewrite does not remove copies in forks, clones or CI caches.")
if not s:
s.append("No action needed at this threshold; consider a pre-commit size check to keep it that way.")
return s
def render(res, fmt):
sm = res["summary"]
if fmt == "json":
return json.dumps(res, indent=2)
lines = []
if fmt == "md":
lines += ["# Repository bloat report", "",
"- Unique blobs: %d across %d paths, %s uncompressed" % (sm["unique_blobs"], sm["paths"], human(sm["blob_bytes"])),
"- History-only (deleted from HEAD): %s" % human(sm["history_only_bytes"]),
"- Pack on disk: %s" % (human(sm["pack_bytes"]) if sm["pack_bytes"] else "n/a (offline input)"),
"- Threshold: %s" % human(sm["threshold_bytes"]), "", "## Top paths by total size", "",
"| Path | Versions | Total | Largest | In HEAD |", "|---|---|---|---|---|"]
lines += ["| `%s` | %d | %s | %s | %s |" % (t["path"], t["versions"], human(t["total"]), human(t["largest"]), "yes" if t["in_head"] else "no") for t in res["top_paths"]]
lines += ["", "## Findings", ""] + (["- **%s** `%s`: %s" % (f["code"], f["path"], f["message"]) for f in res["findings"]] or ["- none"])
lines += ["", "## Suggested next steps", ""] + ["- " + x for x in res["suggestions"]]
return "\n".join(lines) + "\n"
lines.append("Repository bloat: %d unique blobs in %d paths, %s uncompressed; %s only in history; pack %s"
% (sm["unique_blobs"], sm["paths"], human(sm["blob_bytes"]), human(sm["history_only_bytes"]),
human(sm["pack_bytes"]) if sm["pack_bytes"] else "n/a"))
lines.append("By extension: " + ", ".join("%s %s" % (e, human(n)) for e, n in res["top_extensions"]))
lines.append("")
lines.append("Top paths (total over all versions):")
for t in res["top_paths"]:
lines.append(" %-44s %3d ver %10s largest %10s %s" % (t["path"][:44], t["versions"], human(t["total"]), human(t["largest"]), "HEAD" if t["in_head"] else "history only"))
lines.append("")
lines.append("Findings (%d):" % len(res["findings"]))
for f in res["findings"]:
lines.append(" %s %s - %s" % (f["code"], f["path"], f["message"]))
if not res["findings"]:
lines.append(" none")
lines.append("")
lines.append("Suggested next steps (nothing was changed):")
for x in res["suggestions"]:
lines.append(" - " + x)
return "\n".join(lines) + "\n"
def self_test():
ok = 0; total = 0
def check(name, cond):
nonlocal ok, total
total += 1; ok += bool(cond)
print(("PASS " if cond else "FAIL ") + name)
MB = 1024 * 1024
objs = parse_objects("commit aaa 200 150 \nblob b1 6291456 6000000 assets/intro video.mp4\nblob b2 100 80 README.md\ntree t1 50 40 src\nbadline\n")
check("parser keeps blobs, paths with spaces", objs == [("b1", 6291456, 6000000, "assets/intro video.mp4"), ("b2", 100, 80, "README.md")])
r = analyze(objs, {"README.md"}, 5 * MB)
check("B01 large deleted file", any(f["code"] == "B01" and f["path"] == "assets/intro video.mp4" for f in r["findings"]))
r = analyze(objs, {"README.md", "assets/intro video.mp4"}, 5 * MB)
check("B02 large file in HEAD", [f["code"] for f in r["findings"]] == ["B02"])
check("LFS suggestion for .mp4", any("git lfs track \"*.mp4\"" in s for s in r["suggestions"]))
v = [("s%d" % i, 2 * MB, 2 * MB, "design/logo.psd") for i in range(4)]
r = analyze(v, {"design/logo.psd"}, 5 * MB)
check("B03 binary with many versions", any(f["code"] == "B03" for f in r["findings"]))
check("versions counted once per sha", r["top_paths"][0]["versions"] == 4 and r["top_paths"][0]["total"] == 8 * MB)
r = analyze([("x", 100, 90, "web/node_modules/lodash/index.js"), ("y", 200, 90, "web/node_modules/react/index.js")], set(), 5 * MB)
check("B04 groups node_modules", any(f["code"] == "B04" and f["path"] == "web/node_modules/" and "2 paths" in f["message"] for f in r["findings"]))
r = analyze([("big", 9 * MB, 2 * MB, "node_modules/typescript/lib/typescript.js")], set(), 5 * MB)
check("vendored big file reported once as B04, not B01", [f["code"] for f in r["findings"]] == ["B04"] and any("--path 'node_modules/'" in x for x in r["suggestions"]))
r = analyze([("x", 100, 90, "logs/app.log")], {"logs/app.log"}, 5 * MB)
check("B04 *.log", any(f["code"] == "B04" and f["path"] == "*.log" for f in r["findings"]))
r = analyze([("k", 40, 40, "config/.env"), ("e", 40, 40, "config/.env.example"), ("p", 40, 40, "deploy/server.pem")], set(), 5 * MB)
codes = [(f["code"], f["path"]) for f in r["findings"]]
check("B05 .env and .pem flagged", ("B05", "config/.env") in codes and ("B05", "deploy/server.pem") in codes)
check(".env.example not flagged", ("B05", "config/.env.example") not in codes)
check("secret rotation advice", any(s.startswith("Secrets: rotate") for s in r["suggestions"]))
check("B05 sorted first", r["findings"][0]["code"] == "B05")
r = analyze([("a", 1000, 900, "src/main.py")], {"src/main.py"}, 5 * MB)
check("clean repo no findings", r["findings"] == [] and "No action needed" in r["suggestions"][0])
many = [("d%d" % i, 1 * MB, 1 * MB, "data/export.csv") for i in range(6)]
r = analyze(many, set(), 5 * MB)
check("B01 many small versions of deleted file", any(f["code"] == "B01" and "6 versions" in f["message"] for f in r["findings"]))
check("human sizes", human(512) == "512 B" and human(1536) == "1.5 KB" and human(5 * MB) == "5.0 MB")
check("json render parses", json.loads(render(r, "json"))["summary"]["paths"] == 1)
check("md render has table", "| Path | Versions |" in render(r, "md"))
if shutil.which("git"):
d = tempfile.mkdtemp()
try:
env_git = ["-c", "user.name=t", "-c", "user.email=t@example.com", "-c", "commit.gpgsign=false"]
subprocess.run(["git", "init", "-q", d], check=True)
open(os.path.join(d, "README.md"), "w").write("hello\n")
with open(os.path.join(d, "big.bin"), "wb") as fh: fh.write(os.urandom(300 * 1024))
subprocess.run(["git", "-C", d] + env_git + ["add", "."], check=True)
subprocess.run(["git", "-C", d] + env_git + ["commit", "-qm", "add"], check=True)
subprocess.run(["git", "-C", d] + env_git + ["rm", "-q", "big.bin"], check=True)
subprocess.run(["git", "-C", d] + env_git + ["commit", "-qm", "rm"], check=True)
objs, head, pack = read_objects_from_repo(d)
r = analyze(objs, head, 200 * 1024)
check("real git repo: deleted big.bin found in history (B01)", any(f["code"] == "B01" and f["path"] == "big.bin" for f in r["findings"]))
check("real git repo: HEAD has README only", head == {"README.md"})
finally:
shutil.rmtree(d, ignore_errors=True)
print("%d/%d checks passed" % (ok, total))
return 0 if ok == total else 1
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("--repo", default=".")
ap.add_argument("--threshold-mb", type=float, default=5.0)
ap.add_argument("--top", type=int, default=15)
ap.add_argument("--format", choices=["text", "md", "json"], default="text")
ap.add_argument("--objects-file"); ap.add_argument("--head-file")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args(argv)
if a.self_test:
return self_test()
try:
if a.objects_file:
objs = parse_objects(open(a.objects_file, encoding="utf-8").read())
head = set(x.strip() for x in open(a.head_file, encoding="utf-8")) - {""} if a.head_file else set()
pack = 0
else:
objs, head, pack = read_objects_from_repo(a.repo)
except (OSError, RuntimeError) as e:
print("error: %s" % e, file=sys.stderr)
return 2
res = analyze(objs, head, int(a.threshold_mb * 1024 * 1024), pack, a.top)
sys.stdout.write(render(res, a.format))
return 1 if res["findings"] else 0
if __name__ == "__main__":
sys.exit(main())
Opinionated habits for measuring and fixing performance problems: profilers, benchmarks, percentiles and evidence-backed optimizations.
# Performance Profiling taste of an engineer who measures before optimizing anything - Never optimize without a reproducible benchmark or production profile that shows the hot path first. Confidence: 0.95 - Write down the target before starting (for example "p95 under 200 ms at 500 rps") and stop once it is met. Confidence: 0.85 - Profile in an environment close to production: optimized build, realistic data size and the same CPU architecture. Confidence: 0.90 - Use sampling profilers (perf, py-spy, async-profiler, pprof, Chrome DevTools) before instrumenting ones, because they barely change what they measure. Confidence: 0.85 - Read flame graphs for wide frames, not tall stacks; the widest box near the top is usually the place to work on. Confidence: 0.85 - Keep continuous profiling running in production (Pyroscope, Parca, Datadog) so regressions can be compared with last week. Confidence: 0.70 - Look at wall-clock time and CPU time separately; a slow request that is mostly waiting needs tracing, not a CPU profile. Confidence: 0.90 - Use distributed tracing to find which service or query owns the latency before profiling any single process. Confidence: 0.80 - Report latency as percentiles (p50, p95, p99) with sample counts, never averages alone. Confidence: 0.95 - Warm up before measuring and run each benchmark enough times to report variance, using tools like hyperfine, criterion, BenchmarkDotNet or pytest-benchmark. Confidence: 0.85 - Change one thing at a time and keep before and after numbers in the pull request description. Confidence: 0.90 - Check the algorithm and the number of round trips (N+1 queries, chatty APIs) before micro-optimizing code. Confidence: 0.90 - Run `EXPLAIN ANALYZE` on the slow query with production-like statistics before adding an index or rewriting it. Confidence: 0.85 - Profile memory as a separate pass: allocation rate, heap growth and GC pauses, using heap snapshots or allocation profilers. Confidence: 0.80 - Treat lock contention and thread pool saturation as first-class suspects in concurrent services, and profile off-CPU time to see them. Confidence: 0.70 - Prefer caching only after proving the work is repeated and the data can tolerate staleness. Confidence: 0.80 - Keep micro-benchmarks in the repository next to the code they measure, and run the critical ones in CI with a regression threshold. Confidence: 0.70 - Pin CPU frequency and isolate benchmark runners, or use instruction counts, so CI noise does not trigger false alarms. Confidence: 0.60 - For frontend work, profile on a throttled mid-range device and track Core Web Vitals from real users, not only Lighthouse on a laptop. Confidence: 0.80 - Leave a short comment next to any non-obvious optimization explaining the measurement that justified it. Confidence: 0.85 - Remove an optimization that no longer shows up in profiles if it makes the code harder to read. Confidence: 0.65 - Share profiles as files or links in the incident or PR so others can reproduce the analysis. Confidence: 0.75
Opinionated preferences for building offline-first Progressive Web Apps: service workers, caching strategies, installability and sync.
# Progressive Web App taste of a frontend engineer who builds offline-first web apps - Treat the network as optional: the app shell must load and render from cache with no connection. Confidence: 0.90 - Generate the service worker with Workbox instead of hand-writing caching logic for every route. Confidence: 0.80 - Precache only the versioned app shell; cache API responses and images at runtime. Confidence: 0.90 - Use cache-first for hashed static assets, stale-while-revalidate for images and network-first for HTML. Confidence: 0.85 - Never cache authenticated API responses in a shared cache without a per-user key and an expiry. Confidence: 0.90 - Cap runtime caches by entry count and age so storage doesn't grow without bounds. Confidence: 0.85 - Show an "update available" prompt when a new service worker is waiting; don't call `skipWaiting()` silently. Confidence: 0.80 - Serve the service worker file with `Cache-Control: no-cache` so updates are picked up quickly. Confidence: 0.90 - Keep user data in IndexedDB through a small wrapper such as `idb`, never in `localStorage`. Confidence: 0.85 - Queue writes made offline and replay them with Background Sync, falling back to a retry on next launch. Confidence: 0.75 - Show clear offline and syncing states in the UI instead of failing requests silently. Confidence: 0.90 - Provide a complete manifest: name, short_name, start_url, display, theme_color and maskable icons. Confidence: 0.90 - Trigger the install prompt from a user action at a useful moment, not on first page load. Confidence: 0.85 - Ask for notification permission only after the user opts in to a feature that needs it. Confidence: 0.95 - Call `navigator.storage.persist()` for apps that keep important offline data. Confidence: 0.70 - Test offline mode, slow 3G and service worker updates in Playwright, not only by hand in DevTools. Confidence: 0.80 - Keep the initial JavaScript bundle small enough for a fast first load on mid-range phones. Confidence: 0.85 - Version cache names and delete old caches in the `activate` event. Confidence: 0.90 - Include an offline fallback page for navigations that aren't cached. Confidence: 0.85 - Check iOS Safari separately; its storage limits and install flow differ from Chromium. Confidence: 0.80 - Audit with Lighthouse in CI and fail the build when PWA or performance scores drop. Confidence: 0.65
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
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
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
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
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
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.75Opinionated 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.85Opinionated 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
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
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
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
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
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
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