Opinionated data privacy engineering preferences: collect less, classify PII in the schema, keep it out of logs, encrypt and tokenize sensitive fields, and make deletion and export requests boring.
# Data Privacy Engineering taste of a backend engineer who treats PII like radioactive material - Collect the minimum data a feature needs and write down why each personal field exists before adding a column. Confidence: 0.95 - Mark PII and sensitive columns in the schema itself (comments, annotations or a data catalog) so tooling can find them. Confidence: 0.85 - Never log raw emails, phone numbers, tokens, addresses or request bodies; log stable internal ids and redact at the logger level. Confidence: 0.95 - Keep personal data in a small number of well-known tables instead of copying it into every service and event payload. Confidence: 0.85 - Put internal ids, not emails or names, into events, URLs, analytics and error trackers. Confidence: 0.90 - Encrypt highly sensitive fields at the application level with keys in a KMS, on top of disk encryption. Confidence: 0.75 - Tokenize or hash identifiers used for joins and analytics; use a keyed hash (HMAC) so values cannot be reversed with a lookup table. Confidence: 0.80 - Define a retention period for every personal data store and enforce it with a scheduled job, not a policy document. Confidence: 0.90 - Build account deletion as a real pipeline that reaches the primary database, search indexes, caches, object storage and third-party processors. Confidence: 0.90 - Prefer hard deletes or irreversible anonymization for user deletion requests; soft-deleted rows still count as stored data. Confidence: 0.80 - Make data export a tested feature that produces a machine-readable archive of everything stored about a user. Confidence: 0.75 - Remember that backups keep deleted data; document how long they live and make sure restores re-apply pending deletions. Confidence: 0.70 - Keep an up-to-date list of subprocessors and what personal data each one receives. Confidence: 0.80 - Never copy production personal data into staging or local environments; use synthetic or properly anonymized datasets. Confidence: 0.95 - Gate access to production data with least privilege, short-lived credentials and an audit log of who queried what. Confidence: 0.90 - Store consent as versioned records with timestamp and purpose, not as a single boolean column. Confidence: 0.80 - Load analytics and marketing scripts only after consent, and test that they really stay off when consent is declined. Confidence: 0.85 - Strip EXIF and other metadata such as GPS location from user-uploaded images before storing or serving them. Confidence: 0.80 - Add automated checks in CI or code review that flag new PII fields and new third-party data flows. Confidence: 0.65 - Write privacy requirements as acceptance criteria and tests, the same way you write security requirements. Confidence: 0.75
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 test fixtures and seed data preferences: factories over giant fixture files, per-test isolation, deterministic data, a real database in tests and separate dev seeds that never touch production.
# Test Fixtures and Seed Data taste of a backend developer who wants tests that never flake - Use small factory functions with sensible defaults and per-test overrides instead of one huge shared fixture file. Confidence: 0.90 - Each test creates exactly the data it asserts on; never depend on rows another test or a global seed happened to insert. Confidence: 0.95 - Isolate tests with a transaction rolled back after each test, or truncate tables between tests when transactions are not possible. Confidence: 0.85 - Run integration tests against the same database engine as production in a container, not an in-memory substitute with different behavior. Confidence: 0.90 - Apply real migrations to the test database at the start of the run instead of a hand-maintained schema dump. Confidence: 0.85 - Make generated data deterministic: seed the fake-data library and freeze the clock so failures reproduce exactly. Confidence: 0.90 - Generate unique values (emails, slugs) with a sequence or random suffix so parallel tests never collide on unique constraints. Confidence: 0.85 - Keep factories next to the domain model and build valid objects by default; tests should opt in to invalid states explicitly. Confidence: 0.80 - Prefer building objects in memory for unit tests and persisting only in tests that actually need the database. Confidence: 0.80 - Name fixtures by intent, like paidCustomer or expiredSubscription, not user1 and user2. Confidence: 0.75 - Keep golden files and JSON fixtures small, reviewed and regenerated by a script, never edited by hand into drift. Confidence: 0.70 - Keep development seed data separate from test data; seeds exist to make the app usable locally, not to make tests pass. Confidence: 0.85 - Make seed scripts idempotent with upserts so running them twice is safe. Confidence: 0.90 - Guard seed and reset scripts so they refuse to run when the database URL points at production. Confidence: 1.00 - Never copy raw production data into dev or test; use synthetic data or an anonymized, masked snapshot. Confidence: 0.95 - Seed one realistic account per main role (admin, member, viewer) with documented local credentials. Confidence: 0.75 - Include awkward data in seeds: long names, Unicode, empty lists and many rows, so UI and pagination bugs show up early. Confidence: 0.75 - Stub external HTTP calls at the network boundary with recorded responses, and refresh recordings on a schedule. Confidence: 0.80 - Fail the test run on leaked data: assert tables are empty after the suite when using truncate isolation. Confidence: 0.60 - Keep the full integration suite under a few minutes in CI by parallelizing across database schemas or containers. Confidence: 0.70
Opinionated Drizzle ORM preferences: schema in TypeScript, drizzle-kit migrations in git, explicit relations, typed queries, transactions, prepared statements and Zod schemas generated from tables.
# Drizzle ORM taste of a TypeScript developer who likes to see the SQL - Define the schema in TypeScript with drizzle-orm table builders, split into one file per domain and re-exported from a single schema index. Confidence: 0.85 - Generate SQL migrations with drizzle-kit generate, review the SQL by hand and commit it; never use push against production. Confidence: 0.95 - Use drizzle-kit push only on throwaway local or preview databases where losing data is fine. Confidence: 0.80 - Keep drizzle.config.ts small and read the database URL from the environment, never from a committed file. Confidence: 0.90 - Apply migrations in a separate deploy step with the migrator, not on every app boot in every serverless instance. Confidence: 0.85 - Name columns in snake_case in the database and camelCase in TypeScript using the casing option instead of hand-mapping each one. Confidence: 0.75 - Give every table a primary key, created_at and updated_at with database defaults, and use timestamp with time zone. Confidence: 0.85 - Declare foreign keys with references() and an explicit onDelete behavior so the database enforces integrity. Confidence: 0.90 - Add indexes in the table definition for every foreign key and every column you filter or sort on. Confidence: 0.85 - Define relations() for the relational query API and use db.query with "with" for nested reads instead of manual joins. Confidence: 0.75 - Use the SQL-like select builder with explicit joins when you need aggregates, window functions or precise control. Confidence: 0.80 - Select only the columns you need instead of returning whole rows, especially for list endpoints. Confidence: 0.80 - Infer types with $inferSelect and $inferInsert rather than writing duplicate interfaces by hand. Confidence: 0.90 - Generate Zod schemas from tables with drizzle-zod and refine them for API validation. Confidence: 0.75 - Wrap multi-step writes in db.transaction and pass the tx object down instead of the global db. Confidence: 0.90 - Use the sql template tag for raw fragments, which keeps values parameterized; never build SQL with string concatenation. Confidence: 1.00 - Use prepared statements with placeholders for hot queries on long-running servers. Confidence: 0.65 - Use returning() on inserts and updates instead of a second read query. Confidence: 0.80 - Use onConflictDoUpdate for upserts and back it with a real unique index. Confidence: 0.85 - Pick the driver that matches the runtime (node-postgres for servers, the Neon or other HTTP driver for edge and serverless) and keep it in one db module. Confidence: 0.80 - Keep queries in small repository or data-access functions so route handlers never build queries inline. Confidence: 0.70 - Run integration tests against a real Postgres (container or branch database) with migrations applied, not against mocks. Confidence: 0.85 - Seed local data with a typed seed script checked into the repo. Confidence: 0.70
Opinionated payments integration preferences: hosted checkout first, idempotency keys, webhooks as the source of truth, integer money, test clocks, reconciliation and careful refund handling.
# Payments Integration taste of a backend engineer who never wants to double-charge a customer - Start with the provider's hosted checkout or payment element instead of building card forms yourself; it keeps you out of most PCI scope. Confidence: 0.90 - Never let raw card numbers touch your servers or logs; work only with provider tokens, payment method ids and customer ids. Confidence: 1.00 - Store money as integer minor units (cents) plus an ISO currency code; never use floats for amounts. Confidence: 1.00 - Send an idempotency key on every create or capture request, derived from your own order or attempt id, so retries cannot charge twice. Confidence: 0.95 - Treat signed webhooks as the source of truth for payment state; the browser redirect after checkout is only a hint to show a pending screen. Confidence: 0.95 - Verify every webhook signature against the raw request body before parsing it, and reject events with stale timestamps. Confidence: 1.00 - Make webhook handlers idempotent by recording processed event ids, because providers deliver at least once and out of order. Confidence: 0.90 - Acknowledge webhooks quickly with a 2xx and push the real work onto a background job queue. Confidence: 0.85 - Model orders and payments as explicit state machines (pending, requires_action, succeeded, failed, refunded) and reject impossible transitions. Confidence: 0.85 - Keep your own payments table that maps provider ids to internal order and customer ids; never rely on searching the provider by metadata. Confidence: 0.85 - Put your internal order id in provider metadata too, so support can jump from a dashboard charge to your admin page. Confidence: 0.75 - Calculate prices, discounts and tax on the server from your own catalog; never trust an amount sent by the client. Confidence: 1.00 - Handle 3D Secure and other customer actions with the provider's SDK flow instead of assuming every payment succeeds immediately. Confidence: 0.85 - Use the provider's test mode, test cards and test clocks in CI to cover declines, disputes and subscription renewals. Confidence: 0.80 - Let the provider own subscription billing cycles, proration and dunning unless you have a very strong reason to build it. Confidence: 0.80 - Grant and revoke access from subscription status events, and give a short grace period on failed renewals before locking accounts. Confidence: 0.75 - Run a daily reconciliation job that compares provider balance transactions and payouts with your ledger and alerts on any mismatch. Confidence: 0.85 - Issue refunds through one internal service that records who refunded, why and how much, with partial refunds as first-class records. Confidence: 0.80 - Keep API keys in a secrets manager, use restricted keys per service and rotate them on a schedule. Confidence: 0.90 - Log provider request ids and event ids on every call so disputes and support tickets can be traced end to end. Confidence: 0.80 - Show clear, localized error messages for declines without exposing raw decline codes that help card testers. Confidence: 0.70 - Rate-limit checkout and payment-method endpoints and add bot protection to stop card-testing attacks. Confidence: 0.85 - Wrap the provider behind a thin internal interface, but do not pretend multiple providers are interchangeable until you actually run two. Confidence: 0.65
Opinionated Supabase preferences: migrations in git, Row Level Security on every table, generated types, server-side auth, Edge Functions, storage policies and safe key handling.
# Supabase App taste of a full-stack developer who treats Postgres as the real backend
- Manage the schema with Supabase CLI migrations checked into git; never change production tables in the dashboard. Confidence: 0.95
- Run the local stack with supabase start and test every migration locally before pushing it. Confidence: 0.85
- Enable Row Level Security on every table in exposed schemas, including tables you think nobody can reach. Confidence: 1.00
- Write separate RLS policies per operation (select, insert, update, delete) instead of one broad "for all" policy. Confidence: 0.80
- Wrap auth.uid() in a select inside policies and index the columns policies filter on, so RLS stays fast on large tables. Confidence: 0.80
- Test RLS policies with pgTAP or SQL tests that act as different roles and users. Confidence: 0.80
- Never ship the service role key to the browser or a mobile app; use it only in server code and Edge Functions. Confidence: 1.00
- Generate TypeScript types with supabase gen types after each migration and commit them with the schema change. Confidence: 0.85
- Use @supabase/ssr with cookie-based sessions for server-rendered apps, and check the user with getUser() on the server, not getSession(). Confidence: 0.85
- Keep user profile data in a public profiles table keyed by the auth user id, created by a trigger on auth.users. Confidence: 0.80
- Put multi-row business logic in Postgres functions called through rpc, so it runs in one transaction. Confidence: 0.80
- Mark functions security invoker by default and use security definer only with a fixed search_path and a written reason. Confidence: 0.85
- Keep private tables and helper functions in a schema that is not exposed through the API. Confidence: 0.80
- Use Edge Functions for webhooks, third-party API calls and secrets, not for plain CRUD that RLS already covers. Confidence: 0.80
- Store files in private storage buckets with policies tied to the object path, such as a folder per user id. Confidence: 0.85
- Serve private files through short-lived signed URLs rather than making buckets public. Confidence: 0.85
- Subscribe to Realtime only on the tables and filters a screen needs, and remember RLS applies to what clients receive. Confidence: 0.75
- Select only the columns you need in queries instead of select('*'), and paginate with range(). Confidence: 0.80
- Seed local and preview databases from seed.sql with fake data; never copy production data down. Confidence: 0.85
- Use branching or a separate staging project for preview deployments, never the production database. Confidence: 0.80
- Turn on point-in-time recovery for production and practice a restore before you need one. Confidence: 0.75
- Review the Security and Performance Advisors in the dashboard after every schema change. Confidence: 0.75Opinionated debugging preferences: reproduce first, shrink the failing case, read the real error, bisect, use debuggers and logs deliberately, and lock every fix in with a test.
# Debugging taste of an engineer who would rather prove a cause than guess one - Reproduce the bug reliably before changing any code; a fix for a bug you cannot reproduce is a guess. Confidence: 0.95 - Write down the exact steps, inputs, versions and environment that trigger the bug in the ticket before you start digging. Confidence: 0.85 - Read the full error message and the whole stack trace, starting from the first frame in your own code, before searching the web. Confidence: 0.90 - Shrink the failing case to the smallest input or code path that still fails; most causes become obvious once the noise is gone. Confidence: 0.90 - Turn the reproduction into a failing automated test first, then make it pass, and keep that test forever. Confidence: 0.90 - Use git bisect when something used to work; let the history find the breaking commit instead of reading diffs by hand. Confidence: 0.85 - Change one thing at a time and re-run; never stack several speculative fixes and hope one of them helped. Confidence: 0.90 - State a hypothesis out loud (or in the ticket) before each experiment, and note what result would disprove it. Confidence: 0.75 - Reach for a real debugger with breakpoints and watch expressions over adding a dozen print statements. Confidence: 0.70 - When printing is the right tool, log the values and their types with clear labels, and delete the temporary logs before merging. Confidence: 0.80 - Check your assumptions explicitly with assertions; the bug usually lives in the thing you were sure about. Confidence: 0.85 - Compare a working and a broken environment side by side (config, env vars, dependency versions, data) instead of staring at code. Confidence: 0.80 - Verify you are running the code you think you are running: clear caches, rebuild, and confirm the version or commit in the logs. Confidence: 0.85 - Look at the actual data in the database, queue or API response; do not debug from what the data is supposed to look like. Confidence: 0.85 - Treat flaky tests as real bugs, usually timing, ordering or shared state, and never just add retries to hide them. Confidence: 0.85 - For race conditions, add structured logs with timestamps and request or thread ids, then reconstruct the order of events. Confidence: 0.75 - Read the source of the library or framework when its behavior surprises you; docs describe intent, code describes reality. Confidence: 0.75 - Time-box solo debugging to about an hour, then explain the problem to a teammate or a rubber duck. Confidence: 0.70 - Fix the root cause rather than the symptom, and search the codebase for the same mistake in other places. Confidence: 0.85 - Never debug in production by editing live code; use feature flags, extra telemetry or a copy of the data instead. Confidence: 0.90 - Write a short note in the pull request on the cause, the fix and how it was verified, so the next person learns from it. Confidence: 0.80 - Add the missing log line, metric or error message that would have made this bug obvious, as part of the fix. Confidence: 0.80
Opinionated preferences for handling user file uploads safely: presigned direct uploads, size and type checks, malware scanning, storage keys, image processing and cleanup.
# File Upload Handling taste of a backend engineer who treats every upload as untrusted - Upload large files directly from the browser to object storage with presigned URLs instead of streaming them through the app server. Confidence: 0.90 - Keep presigned upload URLs short-lived (minutes) and scoped to one object key, content type and maximum size. Confidence: 0.90 - Enforce a maximum file size on the server or storage policy, never only in client-side JavaScript. Confidence: 0.95 - Generate storage keys yourself (for example UUIDs under a tenant prefix); never use the user's filename as the path. Confidence: 0.95 - Store the original filename only as sanitized metadata in the database for display and download names. Confidence: 0.85 - Detect the file type from its magic bytes and check it against an allowlist; do not trust the extension or the Content-Type header. Confidence: 0.90 - Keep uploaded files in a private bucket and serve them through short-lived signed download URLs or an authorized proxy. Confidence: 0.90 - Serve user files from a separate domain with Content-Disposition: attachment for risky types so uploaded HTML or SVG cannot run on your origin. Confidence: 0.85 - Scan uploads for malware asynchronously and keep them in a quarantine state until the scan passes. Confidence: 0.80 - Track each upload as a database row with a status (pending, uploaded, scanned, ready, failed) instead of guessing from storage. Confidence: 0.85 - Confirm completion with a server callback or storage event before attaching the file to a record. Confidence: 0.80 - Use multipart or resumable uploads (S3 multipart, tus) for files over roughly 100 MB. Confidence: 0.75 - Re-encode images server-side, strip EXIF metadata including GPS, and generate fixed thumbnail sizes in a background job. Confidence: 0.85 - Reject or carefully sanitize SVG uploads; treat them as code, not images. Confidence: 0.85 - Store a checksum (SHA-256) for each file to detect corruption and deduplicate when it makes sense. Confidence: 0.70 - Set lifecycle rules that delete abandoned pending uploads and incomplete multipart parts after a day or two. Confidence: 0.85 - Delete files from storage when the owning record is deleted, through a background job that retries. Confidence: 0.80 - Rate-limit upload endpoints per user and per IP, and cap total storage per account. Confidence: 0.80 - Never unzip or parse archives and office documents in the request path; do it in a sandboxed worker with size and depth limits. Confidence: 0.85 - Show upload progress and allow cancel in the UI, with clear errors for wrong type or size. Confidence: 0.75 - Log upload metadata (user, key, size, type, status) but never the file content. Confidence: 0.85 - Test uploads with oversized files, renamed executables, polyglot files and filenames with path traversal characters. Confidence: 0.85
Opinionated preferences for writing readable, correct and fast SQL: formatting, CTEs, joins, NULL handling, window functions, parameters and query plans.
# SQL Query Writing taste of a data-minded engineer who wants queries others can read and trust - Write SQL keywords in uppercase and identifiers in snake_case lowercase, one clause per line. Confidence: 0.80 - Put each selected column on its own line with a leading or trailing comma style used consistently across the repo, enforced by sqlfluff. Confidence: 0.75 - Never use SELECT * in application queries or views; list the columns you need. Confidence: 0.90 - Use explicit JOIN ... ON syntax; never comma joins with conditions in WHERE. Confidence: 0.95 - Give every table a short, meaningful alias and qualify every column once more than one table is involved. Confidence: 0.85 - Break long queries into named CTEs that read top to bottom like steps, instead of nesting subqueries three levels deep. Confidence: 0.85 - Check the grain of a query before joining: know what one row means and confirm joins do not fan out rows. Confidence: 0.90 - Prefer EXISTS over IN with a subquery for existence checks, and NOT EXISTS over NOT IN to avoid the NULL trap. Confidence: 0.85 - Treat NULL deliberately: use IS NULL, COALESCE with a documented default and IS DISTINCT FROM for null-safe comparisons. Confidence: 0.90 - Use window functions (ROW_NUMBER, LAG, SUM OVER) for rankings, deduplication and running totals instead of self-joins. Confidence: 0.85 - Filter on half-open date ranges (created_at >= start AND created_at < end) rather than BETWEEN on timestamps. Confidence: 0.90 - Keep predicates sargable: do not wrap indexed columns in functions or casts inside WHERE. Confidence: 0.85 - Always pass values as bound parameters; never build SQL by concatenating user input. Confidence: 1.00 - Use COUNT(*) for row counts and COUNT(column) only when you mean non-null values. Confidence: 0.80 - Put conditions for outer-joined tables in the ON clause, not the WHERE clause, so a LEFT JOIN stays a LEFT JOIN. Confidence: 0.90 - Use CASE expressions with an explicit ELSE so unexpected values are visible instead of silently NULL. Confidence: 0.75 - Add ORDER BY whenever order matters, including with LIMIT; never rely on the natural row order. Confidence: 0.95 - Paginate large result sets with keyset pagination (WHERE id > last_id) instead of big OFFSET values. Confidence: 0.80 - Run EXPLAIN ANALYZE on any query that touches a large table before shipping it, and keep the plan in the pull request. Confidence: 0.80 - Prefer UNION ALL over UNION unless you actually need duplicate removal. Confidence: 0.85 - Write data-changing statements inside a transaction and check the affected row count before committing. Confidence: 0.90 - Comment the business rule behind non-obvious filters, not what the SQL syntax does. Confidence: 0.75 - Keep reusable queries in version-controlled .sql files or views with tests on small fixture data. Confidence: 0.70
Opinionated htmx preferences for server-rendered web apps: hypermedia endpoints, partial templates, swaps, forms, history, CSRF and when to add a little JavaScript.
# htmx Web App taste of a backend developer who wants interactivity without a SPA - Render HTML on the server and use htmx for interactivity before reaching for React or another client-side framework. Confidence: 0.85 - Make every page work as plain links and forms first, then layer hx-get, hx-post and hx-boost on top as progressive enhancement. Confidence: 0.85 - Return HTML fragments from endpoints, never JSON that the client has to turn into markup. Confidence: 0.90 - Keep fragments as small partial templates that the full page template also includes, so there is one source of markup per component. Confidence: 0.90 - Check the HX-Request header on the server to decide between returning a fragment and the full page for the same URL. Confidence: 0.85 - Prefer hx-target with a stable id and hx-swap="outerHTML" so the swapped element can be swapped again later. Confidence: 0.80 - Use hx-push-url for navigation-like swaps so the back button and shareable URLs keep working. Confidence: 0.85 - Put hx-boost="true" on the body or main nav for cheap SPA-like navigation instead of wiring every link by hand. Confidence: 0.70 - Use hx-swap-oob for secondary updates such as a cart count or flash message instead of a second request. Confidence: 0.75 - Trigger client events from the server with the HX-Trigger response header rather than inline script in fragments. Confidence: 0.80 - Show progress with hx-indicator and the htmx-request CSS class; no hand-written loading-state JavaScript. Confidence: 0.85 - Add hx-disabled-elt on submit buttons so double clicks cannot post a form twice. Confidence: 0.80 - Validate forms on the server and re-render the form fragment with inline errors and the user's values kept. Confidence: 0.90 - Use hx-trigger="keyup changed delay:300ms" for live search, and cancel stale requests with hx-sync. Confidence: 0.80 - Send the CSRF token for every non-GET request through hx-headers on the body or a hidden form field. Confidence: 0.95 - Escape all output in templates by default and never swap in user-supplied HTML. Confidence: 0.95 - Return 422 with the re-rendered form on validation errors and configure htmx to swap that response. Confidence: 0.75 - Use HX-Redirect or HX-Location after a successful POST instead of returning a page fragment for the next screen. Confidence: 0.75 - Keep small client-only behavior (toggles, dropdowns, copy buttons) in Alpine.js or a few lines of vanilla JS, not in extra round trips. Confidence: 0.70 - Vendor a pinned htmx file or load it with a subresource integrity hash; no unpinned CDN script tags. Confidence: 0.85 - Avoid hx-on handlers with long inline scripts; move logic into a small named JS function. Confidence: 0.75 - Test endpoints by asserting on returned HTML with a parser, and cover the main flows with Playwright end-to-end tests. Confidence: 0.80 - Reach for a client-side framework only for genuinely app-like screens such as rich editors or offline-first views. Confidence: 0.70
Opinionated preferences for building CSV import features: streaming parsing, encodings, column mapping, row validation, staging tables, dry runs and error reports.
# CSV Data Import taste of a backend developer who has cleaned up too many broken uploads - Treat every uploaded CSV as untrusted input and validate it fully before writing a single row to the main tables. Confidence: 0.95 - Stream files row by row instead of loading the whole file into memory. Confidence: 0.90 - Use a real CSV parser that handles quotes, embedded newlines and escaped delimiters; never split lines on commas. Confidence: 0.95 - Expect UTF-8, strip a leading BOM, and detect Windows-1252 or other encodings with a clear error instead of guessing silently. Confidence: 0.85 - Detect the delimiter (comma, semicolon, tab) from the header row, and let the user confirm it in the UI. Confidence: 0.75 - Require a header row and map columns by header name, not by position. Confidence: 0.90 - Offer a column-mapping step with saved presets for files exported from common tools. Confidence: 0.75 - Normalize headers (trim, lowercase, collapse spaces) before matching them to known fields. Confidence: 0.80 - Validate each row against a schema (Zod, Pydantic or similar) and collect every error with row and column numbers instead of stopping at the first one. Confidence: 0.90 - Parse dates and numbers with an explicit locale and format; never let 03/04 or 1.234 be interpreted by default. Confidence: 0.90 - Keep money as decimal strings until conversion; never parse it as a float. Confidence: 0.95 - Load valid rows into a staging table first, then move them into real tables in one transaction. Confidence: 0.85 - Make imports idempotent with a natural key or an import-supplied external id, so re-uploading the same file does not create duplicates. Confidence: 0.90 - Show a dry-run preview with counts of rows to create, update and skip before the user commits. Confidence: 0.85 - Let users download a CSV of rejected rows with an extra error column so they can fix and re-upload just those rows. Confidence: 0.85 - Process large files in a background job with progress reporting; keep the request that receives the upload short. Confidence: 0.90 - Enforce limits on file size, row count and column count, and say so in the UI before upload. Confidence: 0.85 - Store the original file and an import record (who, when, counts, status) for audits and support questions. Confidence: 0.80 - Escape cells that start with =, +, -, or @ when exporting data back to CSV to prevent formula injection in spreadsheets. Confidence: 0.90 - Publish a downloadable template file with example rows and a short field reference. Confidence: 0.80 - Write tests with real-world ugly fixtures: Excel exports, BOMs, quoted newlines, trailing empty rows and mixed line endings. Confidence: 0.85 - Log import failures with the import id, not row contents, so personal data stays out of logs. Confidence: 0.85
Opinionated Bun preferences for TypeScript projects: runtime, package manager, bun:test, Bun.serve, env validation, single-file builds and Docker images.
# Bun Project taste of a TypeScript developer who wants one fast tool for everything - Use Bun as the runtime, package manager, test runner and bundler in new TypeScript projects instead of stitching together Node, npm, Jest and esbuild. Confidence: 0.85 - Pin the Bun version in package.json "packageManager" and in CI with oven-sh/setup-bun so every machine runs the same build. Confidence: 0.90 - Commit the text lockfile (bun.lock) and run bun install --frozen-lockfile in CI. Confidence: 0.95 - Write TypeScript directly and let Bun run it; keep tsc only for type checking with "noEmit": true. Confidence: 0.90 - Turn on "strict", "noUncheckedIndexedAccess" and "verbatimModuleSyntax" in tsconfig.json. Confidence: 0.85 - Use ES modules only; no CommonJS require in new code. Confidence: 0.90 - Serve HTTP with Bun.serve and its routes object for small services; reach for Hono when you need middleware and validation. Confidence: 0.80 - Read files with Bun.file and write with Bun.write instead of pulling in fs-extra. Confidence: 0.75 - Use the built-in bun:sqlite for local and embedded data before adding a native SQLite package. Confidence: 0.75 - Prefer Web standard APIs (fetch, Request, Response, URL, crypto.subtle) so code also runs on Node, Deno and edge runtimes. Confidence: 0.85 - Write tests with bun:test (describe, test, expect, mock) and keep them next to the code as *.test.ts. Confidence: 0.85 - Run bun test --coverage in CI and fail the job on new uncovered critical paths, not on a global percentage. Confidence: 0.70 - Load configuration from Bun's automatic .env loading plus a Zod schema that validates process.env at startup. Confidence: 0.85 - Never commit .env files; commit .env.example with every key and a comment. Confidence: 0.95 - Define scripts in package.json (dev, test, typecheck, lint, build) and call them with bun run so CI and humans use the same commands. Confidence: 0.90 - Use bun --watch for dev servers and bun --hot only when in-memory state must survive reloads. Confidence: 0.70 - Build single-file executables with bun build --compile for CLIs and small services shipped to servers. Confidence: 0.75 - Use Biome for linting and formatting to keep the toolchain as fast as the runtime. Confidence: 0.75 - Use Bun workspaces for monorepos and reference internal packages with "workspace:*". Confidence: 0.80 - Check a dependency for native addons or Node-only internals before adopting it, and keep a short list of known-incompatible packages in the README. Confidence: 0.70 - Ship Docker images from the official oven/bun slim image with a multi-stage build and a non-root user. Confidence: 0.80 - Keep Node compatibility as a fallback: run the test suite on Node once a week if the package is published to npm. Confidence: 0.65
Opinionated Pydantic v2 preferences for validating data at the edges of Python backends: separate input and output models, strict settings, discriminated unions and safe serialization.
# Pydantic Models taste of a Python backend developer who wants data checked at the edges - Use Pydantic v2 only and write new code against its API (model_validate, model_dump, field_validator), never the v1 compatibility layer. Confidence: 0.95 - Validate data at the boundaries (HTTP requests, queue messages, config, third-party responses) and pass typed models inward. Confidence: 0.90 - Keep separate models for input, output and storage (UserCreate, UserRead, UserRow) instead of one model with optional fields. Confidence: 0.90 - Set model_config = ConfigDict(extra="forbid") on request models so typos in payloads fail loudly. Confidence: 0.85 - Make value objects and events immutable with frozen=True. Confidence: 0.80 - Prefer precise types over plain str: EmailStr, HttpUrl, UUID, PositiveInt, constr with a pattern, Literal for small enums. Confidence: 0.85 - Use Annotated types with Field constraints and reuse them as named aliases (Slug = Annotated[str, Field(pattern=...)]). Confidence: 0.80 - Put single-field rules in field_validator and cross-field rules in model_validator(mode="after"); keep validators pure with no I/O. Confidence: 0.90 - Model variants with discriminated unions on a type field instead of trying each model in order. Confidence: 0.85 - Use timezone-aware datetimes only (AwareDatetime) and reject naive ones at the boundary. Confidence: 0.85 - Store money as Decimal with fixed places, never float. Confidence: 0.95 - Load settings with pydantic-settings from environment variables, with a prefix per service and SecretStr for secrets. Confidence: 0.90 - Never return ORM objects from an API directly; convert with model_validate(obj, from_attributes=True) into a response model. Confidence: 0.85 - Keep strict mode on for internal messages and allow lax coercion only on user-facing form input. Confidence: 0.70 - Use alias_generator with to_camel when the wire format is camelCase, and keep snake_case attributes in Python. Confidence: 0.80 - Serialize with model_dump(mode="json", exclude_none=True) for APIs so dates and decimals become stable strings. Confidence: 0.75 - Use TypeAdapter for validating plain lists, dicts and unions without wrapping them in a dummy model. Confidence: 0.80 - Export JSON Schema with model_json_schema and commit it, so API clients and docs stay in sync. Confidence: 0.70 - Return validation errors as a list of field paths and messages; never leak the raw exception text to clients. Confidence: 0.85 - Avoid heavy business logic and database calls inside models; models describe shape, services do work. Confidence: 0.85 - Test models with table-driven pytest cases for valid and invalid payloads, plus a few Hypothesis property tests for parsers. Confidence: 0.70 - Run mypy or pyright with the Pydantic plugin in CI so model fields and call sites are type-checked. Confidence: 0.80
Opinionated preferences for reliable RabbitMQ messaging: quorum queues, publisher confirms, manual acks, dead lettering, retries and idempotent consumers.
# RabbitMQ Messaging taste of an engineer who wants every message accounted for - Declare exchanges, queues and bindings in code or a definitions file at startup, never by hand in the management UI. Confidence: 0.90 - Use quorum queues for anything that matters; keep classic queues only for throwaway, non-critical traffic. Confidence: 0.90 - Make queues durable and publish messages as persistent, and enable publisher confirms on every producer. Confidence: 0.95 - Publish to a named topic exchange, never to the default exchange with a queue name as routing key. Confidence: 0.80 - Use routing keys shaped like domain.entity.event (orders.order.created) so consumers bind with wildcards. Confidence: 0.80 - Give each consuming service its own queue bound to the exchange; services never share a queue. Confidence: 0.90 - Turn off auto-ack and ack only after the work and its side effects are committed. Confidence: 0.95 - Set a prefetch (basic.qos) per consumer, starting around 10 to 50, instead of leaving it unlimited. Confidence: 0.85 - Make every consumer idempotent with a message_id and a processed-ids table, because delivery is at least once. Confidence: 0.95 - Configure a dead letter exchange for every work queue and alert when the dead letter queue is not empty. Confidence: 0.90 - Retry with delay through a TTL retry queue or the delivery-limit setting, with a capped number of attempts, never a hot requeue loop. Confidence: 0.85 - Reject poison messages without requeue after the retry limit so one bad payload cannot block the queue. Confidence: 0.85 - Send JSON with a content_type, a schema version field and a stable message type header. Confidence: 0.80 - Keep messages small (under about 128 KB) and put large payloads in object storage with a link in the message. Confidence: 0.80 - Propagate trace context (traceparent) in message headers so traces cross the broker. Confidence: 0.80 - Use the transactional outbox pattern to publish events that must match a database write. Confidence: 0.85 - Open one long-lived connection per process and separate channels for publishing and consuming. Confidence: 0.80 - Set queue length limits or message TTLs on queues that can grow without bound. Confidence: 0.75 - Do not use RabbitMQ as a long-term event log; reach for streams or Kafka when replay is a requirement. Confidence: 0.75 - Monitor queue depth, consumer count, unacked messages and publish and deliver rates with the Prometheus plugin. Confidence: 0.85 - Run a three-node cluster for production and use a separate vhost and user per application with least privilege. Confidence: 0.80 - Test consumers against a real broker in CI with Testcontainers instead of mocking the client library. Confidence: 0.75
Opinionated preferences for structured JSON logging in backend services: fields, levels, trace correlation, redaction and retention.
# Structured Logging taste of a backend engineer who greps logs at 3 a.m. - Emit every log line as a single JSON object on stdout and let the platform ship it; never write log files from the app. Confidence: 0.90 - Use the same core fields everywhere: timestamp, level, service, environment, version, message. Confidence: 0.90 - Write timestamps in UTC as RFC 3339 with milliseconds, never in local time. Confidence: 0.95 - Keep the message a short constant string and put variable data in fields, so "payment failed" stays searchable. Confidence: 0.90 - Use only four levels in practice: debug, info, warn, error; error means someone should look at it. Confidence: 0.80 - Set the log level from an environment variable and allow changing it at runtime without a redeploy. Confidence: 0.75 - Attach trace_id and span_id from OpenTelemetry context to every line so logs join traces. Confidence: 0.90 - Generate or accept a request_id at the edge, return it in a response header, and log it on every line for that request. Confidence: 0.90 - Use a context-bound child logger (request, job, user) instead of passing ids into every log call. Confidence: 0.85 - Log errors with error.type, error.message and error.stack as separate fields, not one interpolated string. Confidence: 0.85 - Log an error once, where it is handled; do not log and rethrow at every layer. Confidence: 0.90 - Never log secrets, tokens, passwords, full card numbers or session cookies; redact them in the logger, not by convention. Confidence: 0.95 - Treat emails, phone numbers and IPs as personal data: hash or drop them unless there is a documented need. Confidence: 0.85 - Write one canonical summary line per request with route, status, duration_ms and user or tenant id. Confidence: 0.80 - Keep durations in a numeric field with the unit in its name (duration_ms), never as "1.2s" text. Confidence: 0.85 - Follow a shared field naming scheme such as OpenTelemetry semantic conventions or ECS instead of inventing names per team. Confidence: 0.75 - Sample noisy success logs (health checks, polling) and never sample errors. Confidence: 0.80 - Use a fast structured logger with no reflection in hot paths: pino in Node, slog or zap in Go, structlog in Python. Confidence: 0.80 - Pretty-print logs only in local development, behind an env flag, and keep production output raw JSON. Confidence: 0.85 - Make logging non-blocking and bounded; dropping debug lines under pressure is better than stalling requests. Confidence: 0.70 - Set retention per level and environment, for example 7 days for debug and 30 days for info and above. Confidence: 0.70 - Alert on metrics derived from logs, not on single log lines, so one bad request does not page anyone. Confidence: 0.80 - Add a test that asserts key log lines and their fields, so a refactor cannot silently break dashboards. 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())
Opinionated conventions for publishing small, stable Java libraries with Maven: pinned plugins, tiny dependency trees, API compatibility checks and Central releases.
# Java Library taste of a developer who ships small, stable Maven artifacts - Target the oldest Java LTS your users still run (usually 17) and set it with maven.compiler.release, not source/target. Confidence: 0.90 - Use the Maven Wrapper (mvnw) and commit it so every build uses the same Maven version. Confidence: 0.90 - Pin every plugin version in pluginManagement; never rely on Maven's default plugin versions. Confidence: 0.95 - Keep runtime dependencies near zero; a library should not drag Guava or Commons into every consumer. Confidence: 0.85 - Mark compile-only and annotation-processor dependencies as provided or optional so they do not leak transitively. Confidence: 0.80 - Ship a module-info.java, or at least an Automatic-Module-Name in the manifest, so JPMS users get a stable module name. Confidence: 0.85 - Put everything not meant for users in an internal package and do not export it from the module. Confidence: 0.85 - Prefer immutable value types (records or final classes with builders) for the public API. Confidence: 0.85 - Never return null from public methods; return Optional for single values and empty collections for lists. Confidence: 0.85 - Throw unchecked exceptions with clear messages, and define one library-specific base exception type. Confidence: 0.75 - Annotate nullability with JSpecify (@NullMarked at package level) so Kotlin and static analysis tools see the contract. Confidence: 0.75 - Use SLF4J as the only logging dependency and never configure a logging backend inside the library. Confidence: 0.90 - Test with JUnit 5 and AssertJ, and keep unit tests runnable with a plain mvn verify and no network. Confidence: 0.90 - Run integration tests with the Failsafe plugin and Testcontainers instead of shared test databases. Confidence: 0.80 - Enforce formatting with Spotless (google-java-format or palantir-java-format) and fail CI on drift. Confidence: 0.80 - Run Error Prone or SpotBugs in CI and treat new warnings as build failures. Confidence: 0.70 - Use japicmp or revapi to block accidental binary-incompatible changes in minor and patch releases. Confidence: 0.85 - Follow semantic versioning strictly; breaking changes wait for a major version with a migration note. Confidence: 0.90 - Publish a BOM when the project has more than one artifact so users can align versions in one place. Confidence: 0.75 - Generate and publish sources and Javadoc jars, and write Javadoc for every public type and method. Confidence: 0.85 - Publish to Maven Central through the Central Portal with signed artifacts, released from CI, never from a laptop. Confidence: 0.85 - Make builds reproducible by setting project.build.outputTimestamp. Confidence: 0.70 - Test the library in CI on every supported Java version with a matrix build. Confidence: 0.85 - Keep a CHANGELOG.md with Added, Changed, Deprecated and Removed sections for each release. Confidence: 0.80 - Deprecate with @Deprecated(since, forRemoval) for at least one minor release before removing an API. Confidence: 0.80
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 Deno conventions for secure, zero-config TypeScript servers and tools: permissions, JSR imports, testing and publishing.
# Deno Project taste of a TypeScript developer who wants secure, zero-config server code - Start with `deno init` and keep a single `deno.json` for tasks, imports, lint, fmt and compiler options; no separate tsconfig or eslintrc. Confidence: 0.90 - Pin dependencies in the `imports` map of `deno.json` with `jsr:` and `npm:` specifiers, and keep version numbers out of source files. Confidence: 0.90 - Prefer JSR packages, starting with `@std/*`, over npm equivalents when both exist. Confidence: 0.80 - Commit `deno.lock` and run CI with `--frozen` so a dependency can never change silently. Confidence: 0.90 - Grant the narrowest permissions possible, scoped to hosts and paths (`--allow-net=api.example.com`, `--allow-read=./data`); never `-A` outside quick local experiments. Confidence: 0.95 - Write the permission flags into the `deno.json` tasks so every developer runs the app with the same sandbox. Confidence: 0.85 - Use `Deno.serve` with a plain `(req: Request) => Response` handler, and add Hono only when routing grows beyond a few paths. Confidence: 0.80 - Stick to Web standard APIs (`fetch`, `Request`, `URL`, `crypto.subtle`, streams) before reaching for Deno-only or Node-compat APIs. Confidence: 0.85 - Treat `node:` imports and npm packages as an escape hatch and keep them out of core domain modules. Confidence: 0.70 - Keep TypeScript strict as Deno ships it and never weaken compiler options to silence errors. Confidence: 0.90 - Use `deno fmt` and `deno lint` with default rules; argue about logic, not formatting. Confidence: 0.85 - Write tests with `Deno.test` and `@std/assert` next to the code as `*_test.ts` files. Confidence: 0.85 - Run `deno test` with the same narrow permissions as production, so missing grants fail in CI and not at runtime. Confidence: 0.75 - Use `t.step` for grouped scenarios and rely on the built-in resource and op sanitizers to catch leaked timers and sockets. Confidence: 0.70 - Collect coverage with `deno test --coverage` and `deno coverage --lcov` without extra tooling. Confidence: 0.65 - Run `deno check` in CI on every entry point, including scripts that are not imported by the main app. Confidence: 0.80 - Read configuration through a single typed module that validates `Deno.env` once at startup and fails fast on missing values. Confidence: 0.85 - Use the `--env-file` flag for local `.env` files instead of a dotenv dependency. Confidence: 0.75 - Use Deno KV for small queues, counters and session data when deploying to Deno Deploy; use Postgres once relations matter. Confidence: 0.60 - Ship single-binary internal tools with `deno compile`, embedding only the permissions the tool needs. Confidence: 0.75 - Publish shared libraries to JSR with explicit `exports`, JSDoc on every public symbol and no slow types, and check them with `deno publish --dry-run`. Confidence: 0.85 - Handle shutdown by listening for `SIGTERM` with `Deno.addSignalListener` and awaiting `server.shutdown()`. Confidence: 0.70 - Use `deno task` for every repeated command instead of a Makefile or npm scripts. Confidence: 0.80
Opinionated preferences for tenant isolation, data modeling and operations in a multi-tenant B2B SaaS.
# Multi-Tenant SaaS taste of a backend architect who builds B2B products - Start with a shared database and a `tenant_id` column on every tenant-owned table; move to schema- or database-per-tenant only for a proven need. Confidence: 0.85 - Make `tenant_id` NOT NULL and part of every composite index and unique constraint on tenant tables. Confidence: 0.90 - Enforce isolation in the database with Postgres row-level security, not only in application code. Confidence: 0.85 - Resolve the tenant once per request from the authenticated session or token, never from a client-supplied header or body field. Confidence: 0.95 - Carry the tenant in a request context and have the data layer scope every query automatically. Confidence: 0.85 - Write a test for each endpoint that proves a user from tenant A gets 404 for tenant B's resources. Confidence: 0.90 - Return 404 instead of 403 for another tenant's resources so ids don't leak existence. Confidence: 0.80 - Use non-guessable ids (UUIDv7 or prefixed random ids) for anything shown in URLs. Confidence: 0.85 - Model users and organizations separately with a membership table, so one user can belong to many tenants. Confidence: 0.90 - Keep roles per membership (owner, admin, member) and check permissions against the membership, not the user. Confidence: 0.85 - Include `tenant_id` in every cache key, queue message, log line and metric label. Confidence: 0.90 - Prefix object storage paths with the tenant id and issue only short-lived signed URLs. Confidence: 0.85 - Apply rate limits and quotas per tenant so one noisy customer can't degrade everyone else. Confidence: 0.85 - Drive plan limits and features from a per-tenant entitlements record, not scattered `if plan == "pro"` checks. Confidence: 0.80 - Run background jobs with an explicit tenant argument; no job ever processes "all tenants" in one unscoped query. Confidence: 0.80 - Run migrations once for the shared schema and keep them backward compatible, since all tenants upgrade together. Confidence: 0.80 - Support tenant-level data export and hard deletion from day one; enterprise customers and GDPR will ask. Confidence: 0.85 - Keep an audit log per tenant of admin actions, logins and permission changes, visible to tenant admins. Confidence: 0.80 - Offer SSO (SAML/OIDC) and SCIM provisioning as tenant settings, not one-off custom code per customer. Confidence: 0.75 - Let support staff impersonate a tenant user only with an explicit, logged, time-limited session. Confidence: 0.85 - Track usage and cost per tenant so pricing decisions are based on real data. Confidence: 0.75 - Avoid per-tenant code branches; express customer differences as configuration. Confidence: 0.80
Opinionated preferences for sending reliable, secure transactional email from a product backend.
# Transactional Email taste of a backend engineer who owns product email delivery
- Send transactional email through a dedicated provider (Postmark, SES, Resend), never from the app server's own SMTP. Confidence: 0.90
- Keep transactional and marketing email on separate sending domains or subdomains so a campaign never hurts password-reset delivery. Confidence: 0.90
- Publish SPF, DKIM and a DMARC policy before the first send, and move DMARC to `p=quarantine` once reports look clean. Confidence: 0.90
- Enqueue every email from a background job; a request handler never waits on the email API. Confidence: 0.95
- Give each send an idempotency key derived from the event (e.g. `order-confirmed:{orderId}`) so retries never send twice. Confidence: 0.85
- Store templates in the repo as code (React Email or MJML), reviewed in pull requests, not edited in the provider dashboard. Confidence: 0.80
- Always send a plain-text part alongside the HTML part. Confidence: 0.85
- Render templates with typed data and fail the build when a template references a missing variable. Confidence: 0.80
- Keep subject lines specific and under about 60 characters; put the key action in the first line of the body. Confidence: 0.70
- Use a no-reply address only when replies truly can't be handled; prefer a monitored reply-to. Confidence: 0.70
- Process bounce and complaint webhooks and suppress those addresses automatically. Confidence: 0.95
- Verify webhook signatures from the provider before trusting any event. Confidence: 0.90
- Log a message id per send and link it to the user and the triggering event for support lookups. Confidence: 0.85
- Never put secrets, full card numbers or raw reset tokens in logs; log only the message id and template name. Confidence: 0.90
- Make magic links and reset links single-use, short-lived (15-60 minutes) and bound to the account. Confidence: 0.90
- Route all email in development and staging to a catcher like Mailpit; real addresses never receive non-production mail. Confidence: 0.95
- Snapshot-test rendered HTML for each template and send a test batch to Gmail, Outlook and Apple Mail before big template changes. Confidence: 0.75
- Respect user notification preferences for every non-critical email; security and billing emails are the only exceptions. Confidence: 0.85
- Add `List-Unsubscribe` and one-click unsubscribe headers to any email that isn't strictly transactional. Confidence: 0.85
- Localize templates by the user's saved locale, with an English fallback, and format dates in the user's time zone. Confidence: 0.80
- Rate-limit per recipient so a bug can't send hundreds of emails to one person. Confidence: 0.85
- Monitor delivery, bounce and complaint rates with alerts; a complaint rate above 0.1% is an incident. Confidence: 0.80
- Warm up a new sending domain or dedicated IP gradually instead of switching all traffic at once. Confidence: 0.75Opinionated rules for storing, parsing, formatting and testing dates, times and time zones in application code.
# Date and Time Handling taste of a backend developer who has debugged too many off-by-one-hour bugs
- Store instants as UTC timestamps (`timestamptz` in PostgreSQL), never as local wall-clock time without an offset. Confidence: 0.95
- Keep "instant" and "calendar date" as different types: a birthday or due date is a plain date, not midnight UTC. Confidence: 0.90
- Store the user's IANA time zone name (`Europe/Istanbul`), never a fixed offset like `+03:00`, because offsets change with DST and politics. Confidence: 0.90
- Convert to the user's zone only at the edges: rendering, parsing user input and scheduling. Confidence: 0.90
- Serialize timestamps in APIs as ISO 8601 / RFC 3339 strings with an explicit `Z` or offset; avoid bare epoch numbers in public payloads. Confidence: 0.85
- Never parse dates with ad-hoc regexes or `new Date(string)` on non-ISO input; use a strict parser with an explicit format. Confidence: 0.90
- Prefer the Temporal API (or a polyfill) for new JavaScript/TypeScript code; fall back to date-fns or Luxon, not Moment.js. Confidence: 0.80
- Format for humans with `Intl.DateTimeFormat` and the user's locale instead of hand-built strings. Confidence: 0.85
- Store future local events (meetings, reminders) as local date-time plus zone, and compute the UTC instant when needed, so DST rule changes don't shift them. Confidence: 0.85
- Model ranges as half-open intervals `[start, end)` to avoid overlap and double-counting at boundaries. Confidence: 0.90
- Do day arithmetic in calendar terms ("add 1 day" in the user's zone), not by adding 86,400 seconds. Confidence: 0.85
- Use a monotonic clock (`performance.now()`, `time.monotonic()`) for measuring durations and timeouts, never wall-clock time. Confidence: 0.95
- Inject a clock dependency instead of calling `Date.now()` directly in business logic, so tests can freeze and advance time. Confidence: 0.90
- Add tests around DST transitions, leap days, month ends and the year boundary for any scheduling code. Confidence: 0.85
- Run the test suite at least once with a non-UTC `TZ` environment variable to catch hidden local-time assumptions. Confidence: 0.75
- Keep server, database and container clocks in UTC and synced with NTP. Confidence: 0.90
- Never compare or sort dates as formatted strings unless they are fixed-width ISO 8601 in the same zone. Confidence: 0.80
- Keep the time zone database (tzdata) up to date in runtimes and container images. Confidence: 0.75
- Show relative times ("3 hours ago") only alongside an absolute timestamp available on hover or in detail views. Confidence: 0.65
- Name fields with their meaning and unit: `createdAt`, `expiresAt`, `timeoutMs`, never just `time` or `date`. Confidence: 0.85
- Treat leap seconds as the platform's problem; don't build application logic that depends on them. Confidence: 0.70
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 Node.js and TypeScript service conventions for small, observable APIs that start fast and shut down cleanly.
# Node.js Backend Service taste of a TypeScript engineer who wants small, predictable services - Write services in TypeScript with `strict: true` and native ES modules. Confidence: 0.90 - Pin the Node.js version to an active LTS release in `.nvmrc`, `engines` and the Docker base image. Confidence: 0.90 - Use Fastify or Hono for HTTP, with request and response schemas that also generate the OpenAPI document. Confidence: 0.75 - Validate every incoming body, query and header at the edge and work only with typed data inside. Confidence: 0.95 - Load configuration once at startup from environment variables, validate it with a schema and fail fast if anything is missing. Confidence: 0.90 - Keep handlers thin: they parse input, call a service function and map the result to a response. Confidence: 0.85 - Never block the event loop; move CPU-heavy work to worker threads or a separate job queue. Confidence: 0.90 - Use `async`/`await` everywhere and treat any floating promise as a lint error. Confidence: 0.90 - Log structured JSON with pino, include a request ID on every line and never log secrets or tokens. Confidence: 0.90 - Return errors in one consistent JSON shape with a stable error code, and map unknown errors to 500 without leaking stack traces. Confidence: 0.85 - Handle `SIGTERM` by closing the server, draining in-flight requests and closing database pools before exit. Confidence: 0.90 - Crash on `unhandledRejection` and `uncaughtException` after logging, and let the orchestrator restart the process. Confidence: 0.80 - Expose separate liveness and readiness endpoints; readiness checks real dependencies. Confidence: 0.85 - Set timeouts on every outgoing HTTP and database call, and use `AbortSignal` to cancel them. Confidence: 0.85 - Use a connection pool with a fixed maximum size for the database, tuned to the number of instances. Confidence: 0.80 - Prefer the built-in `fetch`, `node:test` and `node:crypto` before adding a dependency. Confidence: 0.70 - Test HTTP routes with in-process injection instead of starting a real port. Confidence: 0.75 - Add OpenTelemetry tracing early so slow requests can be followed across services. Confidence: 0.75 - Build a small production image with a multi-stage Dockerfile and run it as a non-root user. Confidence: 0.85 - Keep `package-lock.json` committed and install with `npm ci` in CI and Docker builds. Confidence: 0.90