Scale Check — 7-Point Production Readiness Audit
You are running /scale-check in read-only plan mode. Your job is to inspect the codebase against the 7 scaling questions below and put a clear, prioritized verification and fix plan on the user's screen.
Target Scope: $ARGUMENTS (If empty, audit the entire repository).
Iron Rules (Read Before Scanning)
- Look, do not change: You are strictly in diagnostic and planning mode. Do NOT create, edit, or delete any files. Do NOT run database migrations, state-changing commands, or network requests.
- Findings are leads to check, not facts: Static repository analysis cannot see external cloud dashboards, CDN rules, WAF policies, or managed database settings. Frame every issue you spot as a lead to verify, never as a guaranteed bug.
- Always cite exact locations: Every code lead must include
path/to/file:lineand the specific symbol or query involved. If something is missing from the codebase, explicitly report: "Not found in repo — verify in your hosting/cloud provider." - Fix one at a time, starting with survival: Always order the final remediation plan starting with Backups (Question 5) and Rate Limiting (Question 7), then any private data leaking through a shared cache (Question 6), then the remaining questions in the order they usually hit a growing app: indexes and loops (Q1), shared reads (Q2), running as two copies (Q3), slow work in requests (Q4), and public asset caching (the rest of Q6).
Execution Workflow
Phase 1: Fingerprint the Stack (Fast Pass)
Before checking the 7 questions, quickly identify the project's stack so you look in the right places:
- Manifests & Frameworks: Check
package.json,pyproject.toml,requirements.txt,go.mod,Cargo.toml, orGemfile. - Database & ORM: Locate
schema.prisma, Drizzle schema files, TypeORM/Sequelize models, SQLAlchemy/Alembic files, Djangomodels.py, or raw.sqlmigrations. - Entrypoints & Routes: Locate API routes (
app/api/,pages/api/,src/routes/,controllers/,routers/,main.py,cmd/). - Infra & Config: Check
Dockerfile,docker-compose.yml,vercel.json,next.config.*,fly.toml,render.yaml,nginx.conf,.github/workflows/, andREADME.md.
Phase 2: Investigate All 7 Questions
Run targeted Glob, Grep, and Read passes for each of the 7 questions below. Do not skip any question.
The 7 Questions
Question 1: Indexes & Queries Inside Loops
- Card Short Form: "Pages that search or list data: are the columns indexed, and is there any query inside a loop?"
- Full Diagnostic Question: Where does the application list, filter, sort, or search records, are the underlying database columns (
WHERE,JOIN,ORDER BY, foreign keys) backed by indexes in the schema, and does any endpoint execute a database or API query inside a loop (the N+1 problem) or fetch unbounded rows without pagination? - Where & How to Look:
- Schema vs. Queries: Compare list/search queries (
findMany,select,filter,WHERE,ILIKE,ORDER BY) against index definitions (@@index,index(),CREATE INDEX,db_index=True). Note that Prisma/SQLAlchemy often do not auto-index foreign keys or sort columns unless explicitly declared. - Loops with I/O: Grep route handlers and service functions for
for (,for await,.map(async,forEach(async, or list comprehensions that calldb.,prisma.,supabase.,session.execute, orfetch(inside the iteration body. - Unbounded Reads: Check if list endpoints enforce a
take/limitcap or if a single request can load an entire table into memory.
- Schema vs. Queries: Compare list/search queries (
- What Could Be Outside the Repo (False-Positive Check):
- Indexes may have been created manually in production SQL consoles without being committed to migration files.
- Small lookup tables (e.g., <50 static roles or categories) won't bottleneck on a missing index, though N+1 loops over user-generated data will.
Question 2: Repeated Shared Reads
- Card Short Form: "Read queries that run often and return the same result for everyone."
- Full Diagnostic Question: Which high-traffic read queries compute or fetch the exact same public data for every visitor on every request—such as landing page feeds, product catalogs, global configuration, leaderboards, or public counts—without caching the result in memory, Redis/KV, or the framework's data cache?
- Where & How to Look:
- Inspect public routes, homepages, layout loaders, and global middleware that hit the primary database on every page load without user-specific parameters (
userId,sessionId,orgId). - Check for expensive aggregations (
COUNT(*),SUM(), multi-table joins) running live on public endpoints. - Look for existing cache primitives (
unstable_cache,'use cache',revalidate, Redisget/set,@lru_cache,Cache-Control: s-maxage) to see if shared reads are already wrapped.
- Inspect public routes, homepages, layout loaders, and global middleware that hit the primary database on every page load without user-specific parameters (
- What Could Be Outside the Repo (False-Positive Check):
- An upstream CDN (Cloudflare, CloudFront, Fastly) might already cache full public routes at the edge via dashboard page rules.
Question 3: Running as Two Copies (Statelessness & Local Storage)
- Card Short Form: "Could the app run as two copies, and what lives in one server's memory or on its disk?"
- Full Diagnostic Question: If traffic spikes and you spin up a second server instance behind a load balancer (or deploy to auto-scaling serverless instances), what breaks because state is stored in a single process's RAM or written to a single container's local filesystem?
- Where & How to Look:
- In-Process Memory State: Grep for module-level
new Map(),new Set(), global mutable arrays/objects, in-memory session stores (MemoryStore), local rate-limit counters, or in-process pub/sub (EventEmitter, unbridged WebSocketSets) that assume all users hit the same Node/Python/Go process. - Local Disk Dependency: Grep for local file writes (
fs.writeFile,fs.createWriteStream,open(..., 'w'),multer.diskStorage,/tmpor./uploadsstorage) and local embedded databases (sqlite,better-sqlite3,.dbfiles) used for mutable runtime data. - In-Process Cron Jobs: Check for
node-cron,setInterval, orAPSchedulerbooted inside the main web server entrypoint, which would fire duplicate jobs if two instances run simultaneously.
- In-Process Memory State: Grep for module-level
- What Could Be Outside the Repo (False-Positive Check):
- Module-level
Maps used strictly as read-only caches with a TTL (or lazy singleton SDK clients like Prisma/Stripe) are safe across multiple instances. - Single-VPS apps using a mounted persistent volume and sticky sessions may intentionally run as a single node—flag the trade-off clearly rather than calling it broken.
- Module-level
Question 4: Slow Synchronous Work Inside Web Requests
- Card Short Form: "Anywhere a web request does something slow, such as an AI call, an email or a file."
- Full Diagnostic Question: Where does an HTTP request keep the user's connection open while waiting on slow, unpredictable, or heavy work—such as an LLM/AI generation call, sending transactional emails, generating PDFs, resizing images/videos, parsing large CSVs, or chaining multiple third-party webhooks—before returning a response?
- Where & How to Look:
- Trace
POST/PUTcontrollers, Server Actions, and webhook handlers from request start to response return. - Grep for blocking
awaitcalls to AI SDKs (openai,@anthropic-ai,@google/genai,ai), email providers (resend,nodemailer,sendgrid,postmark), media/file processors (sharp,ffmpeg,puppeteer,pdfkit), or external APIs inside the critical request path. - Check whether the project has a background queue or async worker setup (
bullmq,inngest,trigger.dev,celery,sidekiq,waitUntil) and whether slow calls actually use it or bypass it.
- Trace
- What Could Be Outside the Repo (False-Positive Check):
- Streaming AI endpoints (
streamText, SSE, chunked responses) are designed to stay open while streaming tokens to the client; flag them only if they do heavy synchronous pre/post-processing or lack timeout bounds.
- Streaming AI endpoints (
Question 5: Backups, Replicas & Restore Path
- Card Short Form: "What backups or replicas exist, where, how often, and how to restore. If it isn't in the repo, say so."
- Full Diagnostic Question: What automated database and storage backups or replicas exist, where are they stored, how frequently do they run, and is there a documented, tested procedure to restore them? If backup configuration is not visible in the repository, state that explicitly.
- Where & How to Look:
- Search infrastructure files (
docker-compose.yml, Terraform.tf, Pulumi, CloudFormation,fly.toml,.github/workflows/,scripts/,Makefile,crontab) forpg_dump,mysqldump,sqlite3 .backup,wal-g,litestream, S3 backup syncs, or replica configurations. - Search
README.md,CONTRIBUTING.md,docs/, orrunbooks/for any mention of backup schedules, Point-in-Time Recovery (PITR), or restore commands.
- Search infrastructure files (
- Mandatory Rule for Question 5:
- In most modern apps using managed databases (Supabase, Neon, RDS, PlanetScale, Railway, MongoDB Atlas), backup settings live in the cloud dashboard, not in git.
- If you do not find backup configs and restore instructions in the repo, say so plainly: "No backup configuration or restore runbook found in the repository. Verify in your database provider's dashboard that automated backups/PITR are enabled, check retention frequency, and run a test restore into a staging database."
Question 6: Public Assets vs. Private Data Caching
- Card Short Form: "Which files are the same for every user, and which must never be cached."
- Full Diagnostic Question: Are static files that are identical for every user (bundles, fonts, public images, marketing pages) configured to be cached aggressively at the CDN/browser edge, and are authenticated or user-specific responses (account data, dashboards, billing, auth tokens) strictly protected from being stored in a shared cache?
- Where & How to Look:
- Dangerous Cache Leaks (P0 risk): Check if any route returning personalized data, session state, or private JSON sets
Cache-Control: publicors-maxagewithoutprivateorno-store, or if framework route caching (export const revalidate = ...,force-static) is accidentally enabled on a route that reads cookies/headers for a specific user. - Uncached Static Assets: Check
next.config.*,vercel.json,nginx.conf, Expressstatic(), or S3/CDN upload helpers to see if static assets and user-uploaded public media set immutable or long-livedCache-Controlheaders.
- Dangerous Cache Leaks (P0 risk): Check if any route returning personalized data, session state, or private JSON sets
- What Could Be Outside the Repo (False-Positive Check):
- Frameworks like Next.js, Remix, and Vite automatically fingerprint and cache build assets under
/_next/staticor/assetsat deploy time even without custom headers in the repo.
- Frameworks like Next.js, Remix, and Vite automatically fingerprint and cache build assets under
Question 7: Public & Paid Endpoints (Rate Limiting & Cost Guards)
- Card Short Form: "Which endpoints are public or call a paid service, and does anything limit how often one user can call them."
- Full Diagnostic Question: Which routes can be called without authentication (login, signup, magic links, password reset, public search, contact forms, webhooks) or trigger a metered/paid service (LLM APIs, SMS/OTP, email sending, file storage, paid data APIs), and what enforces per-IP or per-user rate limits, request body size caps, and spend/token limits in code?
- Where & How to Look:
- Inventory High-Risk Endpoints: List all public auth/form routes and every endpoint that calls a billed external API or triggers heavy DB writes.
- Check for Rate Limiters: Grep dependencies and middleware for rate-limiting libraries (
@upstash/ratelimit,express-rate-limit,rate-limiter-flexible,slowapi,django-ratelimit,rack-attack,golang.org/x/time/rate) and verify whether they are actually attached to the risky routes. - Check Input & Spend Caps: On AI or file-upload endpoints, check if
max_tokens/maxOutputTokens, prompt length validation (e.g., Zod.max()), and file size limits are enforced before calling the provider.
- What Could Be Outside the Repo (False-Positive Check):
- Rate limiting may be enforced upstream via Cloudflare WAF, AWS API Gateway, Vercel Firewall, or Nginx reverse proxy outside the application repo. If no in-repo limiter exists, flag it as a high-priority lead to verify upstream or add in middleware.
Output Format (Put This Plan on Screen)
Present your report using the exact sections below. Keep the tone direct, calm, and practical.
1. Stack & Scope Snapshot
- Stack Detected: [Framework, Language, DB/ORM, Hosting/Infra hints]
- Scope Scanned: [Full repo or specific path]
- Reminder: These findings are leads to verify, not guaranteed bugs. Infrastructure configured in cloud dashboards (managed DB backups, CDN rules, WAF rate limits) will not appear in git.
2. The 7-Question Scorecard
| # | Question | Status | Top Lead / Observation |
|---|---|---|---|
| Q1 | Search/list indexes & queries in loops | [LEAD TO CHECK] / [LOOKS COVERED] | 1-line summary |
| Q2 | Frequent shared reads returning same data | [LEAD TO CHECK] / [LOOKS COVERED] | 1-line summary |
| Q3 | Running two copies (memory & disk state) | [LEAD TO CHECK] / [LOOKS COVERED] | 1-line summary |
| Q4 | Slow work inside web requests (AI/email/files) | [LEAD TO CHECK] / [LOOKS COVERED] | 1-line summary |
| Q5 | Backups, replicas & restore path | [NOT IN REPO] / [LEAD TO CHECK] / [LOOKS COVERED] | 1-line summary |
| Q6 | Shared static files vs. never-cache private data | [LEAD TO CHECK] / [LOOKS COVERED] | 1-line summary |
| Q7 | Public/paid endpoints & rate limiting | [LEAD TO CHECK] / [LOOKS COVERED] | 1-line summary |
3. Detailed Leads by Question (Q1–Q7)
For each of the 7 questions, provide:
- What we found in the repo: Exact
path/to/file:linereferences and brief description of the pattern (or explicitly state "Not found in repo"). - Why it matters: 1 plain-English sentence on what happens under traffic or failure.
- How to verify: The exact check the developer should do (e.g., an
EXPLAIN ANALYZEquery, a cloud dashboard setting to inspect, or a trace to check) to confirm if this lead needs a fix.
4. Fix-One-At-A-Time Plan (Start with Backups & Rate Limiting)
List the concrete next steps in this exact priority order so the developer can tackle them one by one without breaking working code:
- First — Verify Backups & Restore (Q5): [Specific action to confirm automated backups exist and test a restore, or document the restore steps in the repo]
- Second — Protect Public & Paid Endpoints with Rate Limits (Q7): [Specific endpoints to guard first and where to attach rate limiting / input caps]
- Third — Close Any Private-Data Cache Leak (Q6, private part): [Any route serving user-specific data that a shared cache could store, and the
private, no-storefix. If none was found, say so and move on.] - Fourth — Add Missing Indexes & Unroll N+1 Loops (Q1): [Specific schema columns to index and loop queries to batch]
- Fifth — Cache Frequent Shared Reads (Q2): [Specific high-traffic public queries to wrap in a short TTL cache]
- Sixth — Remove Single-Server Memory/Disk Bottlenecks (Q3): [Specific in-memory stores or local file writes to externalize before running 2+ copies]
- Seventh — Move Slow Request Work Off the Critical Path (Q4): [Specific AI, email, or file calls to stream, queue, or defer]
- Eighth — Cache Public Static Assets (Q6, public part): [Static files and public media that should get long-lived cache headers or a CDN]
Closing Prompt to User
End your report by asking:
"Which single lead would you like to verify or fix first? (Recommended: Step 1 — Backups, or Step 2 — Rate Limiting on
[most exposed endpoint found])."