AI Coding Prompt Library
110 curated prompts that actually work. Copy-ready. Tested in Cursor, Claude Code, Copilot, and Windsurf.
Code Review (10)
Refactoring (10)
Debugging (10)
Documentation (10)
Testing (10)
SQL / Database (10)
Workflow (10)
Security (10)
Performance (8)
API Design (8)
Migration (8)
Architecture (6)
Code Review
Rigorous code review with severity levels
Review the following code as a staff engineer would. For each issue found, categorize as: - BLOCKER: must fix before merge (security, data loss, broken logic) - MAJOR: should fix before merge (perf regression, missing error handling, brittle patterns) - MINOR: nice to fix (style, naming, minor duplication) - NIT: preference only, skip if you disagree Be direct. Show the exact line and a concrete fix. No hedging. No praise for what's fine — only call out problems.
Security-focused review
Audit this code for security issues. Check for: - SQL injection, XSS, CSRF, SSRF - Insecure deserialization - Hardcoded secrets or credentials - Auth bypass, IDOR, privilege escalation - Race conditions in auth or payment flows - Missing rate limiting on sensitive endpoints - Overly permissive CORS or CSP For each issue: line number, severity (Critical/High/Medium/Low), exploitation scenario in 1-2 sentences, exact fix.
Performance regression check
Analyze this diff for performance regressions. Flag: - New N+1 queries - Sync work in async contexts (or vice versa) - Unbounded loops, recursion, or memory growth - New network calls in hot paths - Removed caching or memoization - Blocking calls on the main thread For each finding: severity, expected impact (rough magnitude), and the fix.
PR review as a skeptical reviewer
You are a skeptical senior engineer reviewing this PR. Assume the author is smart but probably missed something. For each change: 1. What's the actual problem being solved? Is this solution over-engineered? 2. Is there a simpler approach that would work? 3. What edge case is untested? 4. What could break in production that dev/staging won't catch? No cheerleading. If it's fine, say 'no issues found' and move on.
Backwards-compatibility check
This code is called by [describe callers or 'multiple external consumers']. Review for backward-compat breaks: - Removed/renamed functions, types, or fields - Changed function signatures - Changed return shapes or error types - Silent behavior changes (e.g., different default, different edge case handling) For each: which callers break, and how to make the change safely (deprecation path, versioning, feature flag).
Accessibility review
Review this UI code for accessibility issues (WCAG 2.2 AA): - Missing labels on inputs / buttons - Missing alt text on images - Insufficient color contrast - Missing ARIA where needed - Keyboard traps or unreachable interactive elements - Focus management on modals/overlays - Missing skip links, landmarks, headings hierarchy For each issue: severity, WCAG criterion, exact fix.
Error handling audit
Audit error handling in this code: - Where are errors swallowed silently? - Where do we throw generic errors that lose context? - Where are we catching too broadly (catching Exception when we mean IOError)? - Where do we handle an error by logging and continuing with bad state? - Where do stack traces leak to users? For each: line, problem, and correct handling.
Concurrency correctness review
This code uses [threads / async / goroutines / actors]. Audit for concurrency bugs: - Data races on shared mutable state - Deadlock potential (lock ordering) - Missed cancellation / context propagation - Fire-and-forget promises/tasks that swallow errors - Unbounded queues / goroutine leaks - Non-reentrant code called reentrantly For each: line, scenario, fix.
Naming and readability review
Review this code purely for naming and readability. For each finding: - Bad name → suggest better name (functions, variables, types) - Long function that should be broken up (name what the extracted piece would be called) - Magic number → suggest constant name - Nested conditionals that should be early returns Be surgical. Only flag things that would actually confuse the next person reading this.
Diff review focused on what CHANGED
Here is a git diff. Review ONLY what changed — do not comment on existing code around the changes unless the change breaks it. For each hunk: - What behavior changed? - What could regress? - Is there a test asserting the new behavior? If the diff looks fine, say so and stop.
Refactoring
Extract function preserving behavior
Extract the highlighted code into a new function. Requirements: - Function name reflects intent, not implementation - Preserve exact behavior — no logic changes - Type-annotate parameters and return - Add a test asserting new function produces the same output as before for at least one representative input - Update the original caller to use the new function Do not touch any code outside the extracted region.
Rename symbol across codebase
Rename `OLD_NAME` to `NEW_NAME` across the entire codebase. Requirements: - Update all references (imports, calls, docstrings) - Update tests - Update config files, env vars, and CI if applicable - Do NOT rename in migration files or vendored code - Show me the list of files changed before applying
Convert callback to async/await
Refactor this callback-based code to use async/await. Requirements: - Preserve the public API signature if possible; otherwise show me the breaking change first - Preserve error propagation semantics - Add tests that verify the async version produces the same outputs - Don't leak Promises into what was previously a sync path
Split a fat function
This function is too long. Split it into smaller functions. Rules: - Each new function does ONE thing that can be named clearly - Extracted functions live in the same file unless they're genuinely reusable - Preserve public API — only the internal decomposition changes - No behavior change; add tests only if none exist Show me the proposed function names + one-line description before extracting.
Kill dead code
Find code that is no longer reachable / no longer called / commented out. For each candidate: - Show the file + lines - Trace why you think it's dead (no callers found via grep, feature flag off permanently, etc.) - Confirm no dynamic references (reflection, string-based dispatch) Do NOT delete anything yet. Give me the list, I'll approve.
Denormalize / normalize a data structure
This data is [currently normalized / currently denormalized]. Refactor to [the opposite] because [reason]. Requirements: - Migration path for existing data - Backward-compat during the transition - Update all read/write sites - Add tests asserting the new shape produces same results as the old shape for representative queries
Replace inheritance with composition
This class hierarchy uses inheritance. Refactor to composition. Requirements: - Preserve the public API of the leaf classes - Extract shared behavior into small collaborator objects, injected via constructor - Add tests for the new collaborators - Show me the target design before making changes
Consolidate duplicate code (rule of three)
Find near-duplicate code blocks (at least 3 instances of similar structure). For each cluster: - Show the duplicated pattern - Propose an abstraction (function, class, generic) that handles all cases - Note any case that DOESN'T fit — if there's a case that would need a special flag, the abstraction is probably wrong Do not extract if only 2 cases exist — that's premature.
Modernize legacy syntax
This code uses old-style [callbacks / class components / var / any / string concatenation / etc.]. Modernize to current idioms. Rules: - Behavior-preserving - Update tests only if the modernization requires it - Do NOT touch code outside the target file - List every idiom change in the summary so I can review the pattern
Move a module without breaking imports
Move `OLD_PATH/file.ts` to `NEW_PATH/file.ts`. Steps: 1. List every file importing from the old path 2. Update all imports 3. Move the file 4. Update any tsconfig/paths aliases if the path is aliased 5. Run typecheck to confirm nothing broke Show me the file list before moving.
Debugging
Systematic bug hunt
This bug: [describe the observed behavior + expected behavior] Do NOT guess at a fix. First: 1. List every hypothesis for the cause, most likely first 2. For each, tell me the ONE piece of evidence that would confirm or eliminate it 3. Suggest the fastest experiment (or grep/log check) to test the top hypothesis Wait for me to run the experiment and share results before proposing a fix.
Flaky test diagnosis
This test passes sometimes and fails other times. Investigate the flakiness. Check for: - Timing / race conditions (setTimeout, Promise.all timing, event ordering) - Test order dependencies (global state, DB pollution, mock leaks) - External dependencies (network, filesystem, clock) - Nondeterministic input (Math.random, Date.now, iteration order) Once identified, propose a fix that eliminates the flakiness, not just papers over it (no retries, no sleep hacks).
Production incident post-mortem prep
Given the following logs + error trace, help me construct a post-mortem draft: - Timeline of events (from the logs) - Immediate cause (what code path broke) - Contributing factors (what let it happen) - Detection (how did we find out; how could we find it faster) - Mitigation (what we did to stop it) - Prevention (what change prevents recurrence) Be factual, not blaming. Focus on system failures, not individuals.
Bisect to find the breaking commit
The code worked at commit A and is broken at commit B. Help me set up a git bisect: 1. Give me the exact `git bisect` commands (start, good A, bad B) 2. Tell me the minimal test command to run at each step to determine good/bad 3. When we find the culprit commit, help me read the diff and identify the exact broken line Do not guess which commit is the cause upfront.
Reproduce a rare production bug locally
Users see [bug] in production. I can't reproduce locally. Help me: 1. List everything that might differ between local and prod (data volume, timezone, region, config, dependencies, load, concurrency, network latency) 2. For each, suggest a way to simulate the prod condition locally 3. Suggest logging or feature flag toggles to add to prod to gather more data Do not propose a fix yet — we need to reproduce first.
Memory leak hunt
This process's memory grows unbounded. Help me hunt the leak: 1. What are the most common causes in [language/runtime]? (retained references, unclosed resources, growing caches, event listener leaks) 2. What tools should I use to profile heap growth? (exact commands) 3. What patterns in this code look suspicious? 4. Suggest the smallest reproducible test that would exhibit the leak Don't guess at a fix; help me find the root cause.
Debug intermittent 500s
This endpoint returns 500 about 1% of the time. Help me diagnose. First: 1. What common causes have 1% failure rates? (upstream timeout, connection pool exhaustion, race condition, cold cache, transient DB error) 2. What logs/metrics should I look at? (exact fields + expected values) 3. What client-side or middleware step might be interfering (auth token refresh, CORS preflight, retry storm)? Suggest a diagnostic dashboard query before proposing a fix.
Reduce a bug to minimal repro
I have a bug that reproduces in a large project but I want a minimal repro for a bug report. Help me: 1. Which pieces of the current code are essential vs incidental to the bug? 2. What's a plausible minimal setup (single file, minimal deps) that would still trigger it? 3. Sketch the minimal repro Goal: get to <50 lines that fails, so I can file it upstream or share for help.
Understand a stack trace
Here is a stack trace: [paste]. Walk me through: 1. What actually failed (which line, which value was wrong) 2. How execution got there (call path summary) 3. What the most likely root cause is (not the immediate cause) 4. What to check next Skip frames that are framework internals unless they matter.
Debug a CI failure that passes locally
This test / build passes on my machine but fails in CI. Help me diagnose: 1. Common local-vs-CI differences: node version, OS, env vars, timezone, filesystem case sensitivity, headless vs headed, resource limits, cache state, parallel test execution 2. What to check in the CI config to isolate the difference 3. What logging to add in the failing step to gather signal Do NOT retry-loop or disable the test — find the difference.
Documentation
Write README for a small project
Write a README for this project. Structure: 1. One-sentence description (what it is + who it's for) 2. Install (exact commands) 3. Quickstart (5 lines max, working code) 4. Configuration (env vars + files) 5. Common tasks (deploy, test, debug) Skip marketing fluff. No emoji. No badges. Assume the reader is a competent dev who wants to get started fast.
API endpoint documentation
For each API endpoint in this file, produce: - Method + path - Purpose (1 sentence) - Request body/query schema with example - Response schema (success + error shapes) with example - Auth requirements - Rate limits - Common errors and their meanings Format as Markdown with headers. Suitable for embedding in an API reference site.
Write CHANGELOG entry
Given this diff, write a CHANGELOG entry in Keep-a-Changelog format: - Category: Added / Changed / Deprecated / Removed / Fixed / Security - User-visible impact (not internal refactoring wording) - Breaking-change flag if applicable - Migration note if breaking One bullet per user-visible change. Skip internal refactors unless they affect users.
Write architecture decision record (ADR)
Write an ADR for the decision to [describe decision]. Use this template: - Title - Status: proposed / accepted / superseded - Context: what problem, what constraints, what forced this decision - Decision: what we chose - Alternatives considered: at least 2, with why we rejected each - Consequences: positive AND negative Be honest about tradeoffs. Do not oversell the choice.
Onboarding doc for a new hire
Write an onboarding doc for a new engineer joining this codebase. Cover: 1. What this project does (business context, not just tech) 2. How to run it locally (day-1 commands) 3. Repo structure at a glance 4. Key concepts unique to this codebase 5. Where to ask for help 6. First good-first-issue to tackle Write for someone senior at their previous job but new here.
Migration guide from v1 to v2
Write a migration guide for users upgrading from [OLD_VERSION] to [NEW_VERSION]. For each breaking change: - Before (code snippet) - After (code snippet) - Why the change was made - Automated codemod if one exists Group changes by area. End with a sanity checklist for testing after migration.
Docstring for a function
Write a docstring for this function. Include: - One-line summary (what it does, not how) - Parameters with type + meaning - Returns with type + meaning - Raises (if applicable) - One usage example if non-obvious Skip anything self-evident from the signature. If the function is genuinely trivial, don't write a docstring — leave it be.
Runbook for an on-call operation
Write a runbook for handling [describe operation, e.g., 'DB failover', 'certificate rotation', 'cache flush']. Format: 1. When to use this runbook (trigger conditions) 2. Preconditions (access, tooling) 3. Steps in order (exact commands) 4. Verification (how to know it worked) 5. Rollback (how to undo) 6. Escalation path if it fails Assume the reader is stressed and half-asleep. No prose paragraphs — commands and checklists only.
Explain a config file
For each field in this config file: - What it does (1 sentence) - Default value - Valid range or type - When you'd want to change it - Side effects of changing it (needs restart? affects other fields?) Markdown table format.
Rewrite docs for clarity
Rewrite this documentation for clarity. Rules: - Cut every sentence that doesn't advance the reader's goal - Replace jargon with plain terms (or define on first use) - Break long paragraphs into scannable lists where structure warrants - Add concrete examples where currently abstract - Keep the same technical facts — only clarify presentation
Testing
Generate tests for existing untested function
This function has no tests. Write a test suite covering: - Happy path (normal expected input) - Boundary cases (empty, single item, max) - Invalid input (wrong type, out of range, null) - Error paths (throws or returns error) Use [testing framework]. Prefer parameterized/table-driven tests where the same assertion runs for multiple inputs. Don't test implementation details, test behavior.
Write a repro test for a bug
There's a bug: [describe]. Before fixing it, write ONE test that reliably reproduces the bug. The test should: - Fail with the current buggy code - Pass once the bug is fixed - Have a name that describes the bug behavior, not the fix - Be self-contained (no external state) Show me the test first. I'll confirm it fails before we fix the bug.
Property-based tests
Write property-based tests for this function using [hypothesis / fast-check / proptest]. For each property: - State the invariant in plain language - Encode it as a property that holds for all valid inputs - Provide a generator for the input Good properties: round-trip (encode then decode = identity), idempotence, monotonicity, invariance under permutation, etc.
Test double: mock vs fake vs stub
This test currently mocks [dependency]. Reconsider: - Is a mock the right tool, or would a fake (in-memory implementation) be better? - Is the mock verifying interactions we care about, or just tightly coupling test to impl? - Would a real instance (with test config) be faster and more accurate? Rewrite the test with the better approach. Explain the choice.
Integration test for a critical flow
Write an integration test for [describe user flow, e.g., 'user signs up, verifies email, logs in']. Requirements: - Uses real DB (test schema, cleaned between runs) - Uses fakes only for third-party services (Stripe, email provider) - Asserts observable outcomes (DB state, response payloads, sent email content) - Not: internal implementation details Setup and teardown minimal — no per-test fixtures if module-level suffices.
Cover a hard-to-test branch
This code has a branch that's hard to test because [reason: depends on time, requires specific network condition, etc.]. Refactor the code to make the branch testable: 1. Inject the hard-to-control dependency (clock, network, filesystem) 2. Provide a test double for it 3. Write the test Do NOT sprinkle `if (isTest)` checks in production code.
Snapshot test for a UI component
Add a snapshot test for this component. Rules: - Snapshot the rendered output for the default state AND 2-3 meaningful variations (loading, error, empty) - Do NOT snapshot random data (timestamps, IDs, generated UUIDs) - Snapshots must be reviewed like code, not blindly updated If the component is highly dynamic, use targeted assertions instead of full snapshots.
Test-time isolation audit
Audit this test suite for isolation issues: - Shared mutable state between tests (globals, singletons, DB rows not cleaned) - Order dependencies (test B relies on test A running first) - Environment leaks (env vars set in one test affecting another) - Mock state not reset between tests Run the suite in random order and in parallel to expose issues. Show me the failures.
Load test setup
I want to load-test this endpoint. Help me set up with [k6 / locust / vegeta]: 1. Realistic request shape + payload 2. Ramp pattern (users over time) 3. Assertions on latency percentiles (p50, p95, p99) + error rate 4. Suggested initial target (start low, we'll ramp) Write the config file. Do not run it yet.
Coverage gap analysis
Given this coverage report, identify the most important untested code: - Untested error paths - Untested branches on business-critical code paths - Untested edge cases (boundary values, empty collections, null) Do not chase coverage for its own sake — focus on code where a bug would matter. Give me the top 5 gaps to add tests for, ranked by risk.
SQL / Database
Optimize slow query
This query is slow: [query]. Explain: 1. What's likely making it slow (based on the query shape — no `EXPLAIN` yet) 2. What indexes should exist for it to be fast 3. Whether the query can be rewritten more efficiently 4. Whether the schema itself is the problem (denormalize? materialized view?) Give me the `EXPLAIN` command to run to verify, then propose the fix based on what I share.
Write a safe migration
I need to [add column / change type / rename / add index] on this table with [N] million rows. Requirements: - Zero downtime (no long locks) - Reversible if it fails - Compatible with the current running code (no breaking changes to callers) - If the change requires app changes, sketch the multi-step migration path Write the migration SQL and describe any coordination needed with deploys.
Design a schema for a new feature
I need to model [feature description]. Design the schema. Include: - Tables with columns + types + nullability + defaults - Primary keys and foreign keys - Indexes to support expected access patterns (list the queries) - Constraints (unique, check) - Migration order (which table first) Before designing, ask about scale, read/write ratio, and any queries I care about.
Add index without downtime
I want to add an index on [table.column]. Give me the safe migration: - Postgres: `CREATE INDEX CONCURRENTLY` + note it can't be in a transaction - MySQL: `ALGORITHM=INPLACE, LOCK=NONE` where possible - Note any gotchas for this specific DB version Also: verify the index will actually be used by the intended queries.
Diagnose deadlock
This log shows a deadlock: [paste]. Help me: 1. Identify the two conflicting transactions 2. Identify the lock ordering violation 3. Propose a fix (consistent lock ordering, shorter transactions, or advisory locks) Do NOT suggest retry-on-deadlock without also fixing the root cause.
Write a data backfill
I need to backfill [column / new table] from existing data. Requirements: - Batched (not one huge transaction) - Idempotent (safe to re-run if partially completed) - Monitorable (log progress) - Non-blocking (won't lock reads/writes on the source table) Write the backfill SQL/script. Estimate runtime for [N] rows.
Normalize / denormalize decision
I'm considering [normalizing X into separate table / denormalizing Y into main table]. Help me decide: - What are the current + expected access patterns? - What's the write vs read ratio? - What's the consistency requirement? - What are the maintenance costs of each approach? Do not just default to 3NF — sometimes denormalized is right.
Query rewrite for correctness
This query returns wrong results in edge cases like [NULL, duplicates, ties, empty sets]. Help me rewrite: - Handle NULLs explicitly (`IS NULL`, `COALESCE`, `NOT EXISTS` vs `NOT IN`) - Handle duplicates (`DISTINCT`, `GROUP BY`) - Handle ties in ORDER BY (add tiebreaker column) - Handle empty result sets (aggregate returns NULL vs 0) Show me the corrected query and a test that exercises each edge case.
Explain a slow EXPLAIN plan
Here is the EXPLAIN ANALYZE output: [paste]. Walk me through: 1. Which node is the bottleneck (highest actual time) 2. Why is it slow (seq scan, hash join spill, sort spill, missing index, bad estimate) 3. What to change (add index, rewrite query, adjust statistics, increase work_mem) Focus on the biggest fix, not micro-optimizations.
Design a soft-delete or audit trail
Add [soft-delete / audit trail] to this table. Design: - Schema changes (columns, indexes, constraints) - App code changes (query filters, write path) - Impact on existing queries - Retention / cleanup policy Warn about pitfalls: soft-delete can make unique constraints tricky; audit tables can grow unbounded.
Workflow
Plan a large refactor without executing
I want to [describe refactor goal]. Do NOT make changes yet. Instead: 1. List every file that will be touched 2. Order the changes so intermediate commits still compile and pass tests 3. Identify any risky steps (breaking changes, data migrations, deploy coordination) 4. Estimate total scope in lines-changed magnitude Wait for my go-ahead before making any changes.
Explain unfamiliar code
I don't understand this code. Explain it as if writing a comment for a future developer. Cover: - What it does (1 sentence) - Why it exists (what problem it solves) - How it works, focusing only on the non-obvious parts - What would break if this code was removed Skip anything self-evident. Assume the reader knows the language and common patterns.
Set up a project from scratch
I want to bootstrap [type of project]. Requirements: [list]. Do NOT run any commands yet. First: 1. Recommend the stack (language, framework, tooling) 2. Justify each choice in one line 3. List the exact commands to bootstrap 4. List the initial directory structure 5. List the initial files to create Wait for my sign-off before creating anything.
Break down a big task into a task list
I want to [describe feature/goal]. Break it into a task list: - Each task is independently reviewable (< 200 lines of diff) - Ordered so each task leaves the codebase in a working state - Marked with rough effort (S/M/L) - Marked with any blockers or dependencies Do not start coding. I'll pick which task to tackle first.
Write a commit message
Write a commit message for this diff. Format: - Subject line: 50 chars max, imperative mood, no period - Blank line - Body: what changed and WHY (not what — the diff shows what) - Reference issue/PR number if in context Skip the body if the subject fully explains it. Do NOT include prompt-generation footers.
Prepare a PR description
Prepare a PR description for this branch. Structure: - Summary: what changed, in 2-3 bullets - Why: the problem this solves - How: the approach, only if non-obvious - Testing: what I did to verify - Screenshots/logs: only if the change is user-visible or fixes a bug - Risk: what could go wrong on rollout, mitigations Skip sections that don't apply. Do not include AI-generation disclaimers.
Estimate scope before starting
I want to [describe task]. Before I start: 1. Estimate scope: XS / S / M / L / XL (in effort-days for one dev) 2. List the unknowns that might blow the estimate 3. Suggest a proof-of-concept subset to de-risk the biggest unknown first Be honest — if you can't estimate without more info, tell me what you need.
Diagnose why a task is stuck
I've been stuck on [describe task] for a while. Help me diagnose: - What's the specific blocker? (understanding, ambiguity, tooling, dependency, motivation) - What's the smallest experiment that would unblock the top hypothesis? - Is the task itself sized wrong (too big to hold in head)? - Should the goal be reframed? Ask me clarifying questions if needed.
Sync from main and resolve conflicts
I have a long-lived branch that's now behind main. Help me: 1. Give me the exact commands to sync (rebase vs merge — recommend which for this case) 2. If conflicts arise, propose a strategy for resolving them (prefer main's version? prefer branch's?) 3. Post-sync verification: what to check to be sure I didn't break my branch Warn about any conflict I should NOT auto-resolve.
Prepare a rollback plan
Before deploying [describe change], help me write the rollback plan: - What signal indicates we need to rollback? (error rate, latency, specific alert) - Exact commands or steps to rollback - How long the rollback takes - What state might be inconsistent post-rollback (migrations run? feature flags flipped?) - Contact / escalation if rollback fails Do not deploy without this.
Security
Threat model a new feature
I'm adding [feature description]. Help me threat-model: - Assets: what data or capability does this expose? - Actors: who could interact with it? (anonymous, authed user, admin, insider) - Threats per STRIDE: Spoofing, Tampering, Repudiation, Info disclosure, DoS, Elevation of privilege - For each realistic threat: severity + mitigation Stay concrete. Do not list generic OWASP items that don't apply.
Audit for injection vulnerabilities
Audit this code for injection vulnerabilities: - SQL: any string concat or interpolation into queries? - Command: any user input passed to shell / exec? - LDAP, XPath, NoSQL: any dynamic query construction? - Template: any user input rendered as template code? - Header: any user input placed in HTTP response headers? For each finding: line, exploit example, fix (parameterization, escaping, validation).
Review authentication logic
Review this auth code for issues: - Timing attacks in password comparison (use constant-time compare) - Token generation entropy (crypto random, not Math.random) - Session fixation, session ID rotation on login - Password storage (proper hashing: bcrypt/argon2, not MD5/SHA) - Rate limiting on login and password reset - Account enumeration via response timing or messages For each: severity + fix.
Audit authorization / IDOR
Audit this code for IDOR (insecure direct object reference): - Every endpoint that takes an object ID: is ownership verified? - Every user-scoped resource: does the query filter by user? - Every admin action: is admin role verified server-side? - Are there hidden endpoints (unlinked but reachable) missing checks? For each finding: line, exploit scenario, fix.
Scan for secrets in code
Scan this codebase for hardcoded secrets: - API keys, tokens, passwords in source - Secrets in comments (even 'temporarily') - Secrets in test fixtures that got committed - Secrets in config files that shouldn't be committed - Base64/hex-encoded strings that might be secrets For each finding: what it is, how to rotate it, how to prevent recurrence (pre-commit hook, gitleaks, etc.).
Review CORS and CSP
Review the CORS and CSP config: - CORS: is `Access-Control-Allow-Origin: *` used on any endpoint returning user data? - CORS: is `credentials: true` combined with a wildcard origin (invalid + insecure)? - CORS: are the allowed methods and headers minimal? - CSP: is `unsafe-inline` or `unsafe-eval` used, and can it be removed? - CSP: are third-party script sources tightly scoped? Suggest tightened config.
Review file upload handling
Review this file upload code: - File type validation (magic bytes, not just extension) - Size limits enforced before reading into memory - Filename sanitization (path traversal, null bytes, unicode tricks) - Storage location (outside webroot, unique names) - Post-upload processing (image parsing, virus scan) — check for parser exploits - Served with correct Content-Type + Content-Disposition For each gap: severity + fix.
Review third-party dependency risk
Review this dependency list for security concerns: - Any packages with known CVEs? (assume I'll run `npm audit` / `pip-audit` — flag which are worth attention) - Any packages with tiny download counts (supply chain risk)? - Any packages that expanded permissions in recent versions? - Any dev dependencies that don't need to be in production? Recommend removals or version pins.
Design rate limiting for an endpoint
Design rate limiting for [endpoint]. Consider: - Key: IP? user? both? - Window: fixed / sliding / token bucket - Limit: what number and why (based on expected legitimate traffic) - Response: 429 with Retry-After? or silent throttling? - Bypass: how do we allow legitimate high-volume clients? - Storage: memory (single-instance) or Redis/KV (distributed)? Write the implementation for the chosen approach.
Post-breach investigation checklist
We suspect a breach in [describe system]. Walk me through investigation: 1. Preserve evidence (which logs to freeze, which snapshots to take) 2. Determine scope (what data, whose data, timeframe) 3. Identify entry point (which vuln, which credential, which endpoint) 4. Contain (revoke tokens, rotate secrets, patch vuln) 5. Communicate (legal obligations, user notification thresholds) Do not touch anything without documenting first.
Performance
Profile before optimizing
This code is slow. Before optimizing, help me profile: 1. What profiler for this language/runtime? (exact command) 2. What signal to look for in the output (CPU-bound? IO-wait? allocations?) 3. How to focus the profile on the hot path (isolate the slow scenario) Do NOT propose optimizations yet — we need data first.
Analyze Big-O of an algorithm
Analyze this function's time + space complexity: - Big-O of the current implementation, worst case - Which input drives the worst case - Whether a lower complexity is achievable, and what tradeoff (space, complexity, constant factor) Do not suggest a rewrite unless the current complexity is genuinely a bottleneck.
Reduce database round trips
This code path makes many DB queries. Help me reduce: 1. Identify N+1 patterns (loop + query inside) 2. Identify sequential queries that could be a single JOIN or batch 3. Identify redundant queries (same data fetched twice) For each: proposed fix (eager load, batch, cache). Estimate the round-trip reduction.
Frontend performance audit
Audit this page for frontend performance: - LCP: what's the largest paint element? Is it optimized (preload, format, dimensions)? - FID/INP: any long tasks blocking main thread? - CLS: any layout shifts from late-loading images/fonts/ads? - Bundle size: any large deps (>50KB gzipped) that could be lazy-loaded or removed? - Fonts: FOUT/FOIT handled? - Images: correct format, sizes attr, lazy loading below fold? Rank fixes by expected impact.
Reduce memory allocation
This hot path allocates too much. Identify allocations: - Object/struct allocations in loops that could be pooled - String concatenation that could be builder pattern - Boxing of primitives - Slice/array growth (pre-size if known) - Closures capturing large context For each: fix. Estimate allocation reduction if we applied all fixes.
Add caching correctly
I want to add a cache for [describe data]. Design: - Layer: in-memory (per-instance) / Redis / CDN? - Key: what identifies uniqueness (include user, region, version, feature flags)? - TTL: how long? why? - Invalidation: on which events? (writes, deploys, schema changes) - Stampede protection: single-flight or probabilistic early refresh? - Consistency: is stale data OK? for how long? Before writing code, agree on these.
Analyze a flame graph
Here is a flame graph (or perf output): [paste or describe]. Walk me through: 1. What function dominates CPU time 2. Whether it's called too often (fix caller) or too slow (fix callee) 3. What in the flame graph shape is suspicious (unexpected wide stacks, unexpected leaf functions) 4. Suggested fix ordered by expected impact Do not micro-optimize functions that don't show up in the profile.
Convert sync to concurrent
This code does N independent operations sequentially. Help me parallelize: 1. Identify which operations are truly independent (no shared mutable state) 2. Choose a concurrency primitive (Promise.all, goroutines, threads, worker pool) 3. Add a bound to concurrency (don't spawn N unbounded) 4. Aggregate errors correctly (fail-fast vs collect-all) 5. Preserve any ordering requirements Show me the design before implementing.
API Design
Design a REST resource
Design a REST API for [resource]. Include: - Resource URIs (nouns, plural, hierarchy) - Methods per URI (GET/POST/PUT/PATCH/DELETE) with body/response shapes - Status codes for success + error cases - Filtering, pagination, sorting parameters - Auth requirements per endpoint - Idempotency guarantees Stick to REST conventions unless there's a specific reason not to. Flag any non-standard choices.
Design pagination
Design pagination for [endpoint]. Choose: - Offset/limit vs cursor-based (default to cursor for real-time / large datasets) - Page size default + max - Response envelope (data + next cursor + hasMore) - Sort stability (ties broken consistently) Justify the choice. If cursor-based, define the cursor encoding (opaque base64 of the sort key).
Design error responses
Design a consistent error response format for this API. Include:
- HTTP status code (correct code for each case)
- Body shape: `{ error: { code, message, details? } }`
- Machine-readable code (stable, versioned)
- Human-readable message (safe to display to users? or is it dev-only?)
- Optional details (validation field errors, retry-after, etc.)
- Correlation ID for support
Apply consistently across all endpoints. Version an existing API
I need to introduce a breaking change to [endpoint]. Design the versioning: - URI-based (`/v2/foo`) vs header-based (`Accept: application/vnd.api.v2+json`) vs query param? - Which existing clients need migration; can we detect them and force v2? - How long do we run both versions in parallel? - Deprecation warning mechanism - Sunset date Write the migration comms + code path.
Design idempotency for a mutation
This endpoint mutates state and can be retried by clients. Design idempotency: - Idempotency key: client-provided header? server-derived from body? - Storage of key -> result (TTL, per-user, per-endpoint) - What if same key comes in with different body (409 conflict)? - What if the original request is still in progress (in-progress lock)? Write the implementation.
GraphQL schema design
Design a GraphQL schema for [feature]. Include: - Types with fields + nullability - Query root fields - Mutation root fields with input types - Subscription root fields (if real-time needed) - Pagination (Relay-style connections) - Error strategy (payload errors vs GraphQL errors) Warn about over-fetching and N+1 pitfalls.
Webhook design
I want to send webhooks for [event]. Design: - Event shape (type, timestamp, resource ID, payload) - Delivery: retry policy, backoff, dead-letter - Signing: HMAC of body with shared secret, header name - Replay protection: timestamp check, nonce - Subscription management: who registers URLs, verification handshake Write the sender + receiver reference implementations.
Rate limit response design
Design the client-facing rate limit contract: - Response status when limited (429) - Headers: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`, `Retry-After` - Different limits per plan/tier: how to communicate - Bulk operations: how do they count against the limit? Document for API consumers.
Migration
Migrate framework version
Migrate this project from [OLD_VERSION] to [NEW_VERSION] of [framework]. Steps: 1. List every breaking change between versions relevant to this codebase 2. For each, identify where our code is affected 3. Order the changes so intermediate states still compile 4. Codemods available? Use them. 5. Test plan for after migration Do not run anything yet — show me the plan.
Migrate DB engine
Migrate from [SOURCE_DB] to [TARGET_DB]. Considerations: - Data type mappings - SQL dialect differences in existing queries - Feature parity (JSON, arrays, generated cols, triggers, extensions) - Migration approach: dual-write, replicate + cutover, batch export/import - Downtime tolerance - Rollback plan Produce the migration playbook.
Migrate from monolith to service
Extract [feature/module] from the monolith into its own service. Plan: 1. Identify the module's boundaries (what data, what code, what deps) 2. Define the interface between monolith and new service (API? events? both?) 3. Migration order: strangler fig — new callers use service, old callers still call monolith code 4. Data ownership: does the service own the data? if so, migration path 5. Deploy topology + observability Start with the interface, not the extraction.
Migrate CI provider
Migrate CI from [OLD] to [NEW]. For each existing job: - What it does - Equivalent config in the new provider - Any behavior differences (caching, secret injection, matrix syntax) - Migration validation (run both in parallel until we trust the new one) Start with the least critical job to build confidence.
Migrate hosting/deploy platform
Migrate from [OLD_PLATFORM] to [NEW_PLATFORM]. Considerations: - App runtime compatibility (Node/Python version, native deps) - Env var / secret migration - Storage / DB connectivity - Domain + SSL cutover - Rollback path - Cost projection Sketch the cutover checklist + timeline.
Migrate from JavaScript to TypeScript
Migrate this JS project to TypeScript incrementally. Plan: 1. `tsconfig.json` with `allowJs: true`, `strict: false` initially 2. Rename files one directory at a time, `.js -> .ts` / `.jsx -> .tsx` 3. Add types starting from the leaves (utils, types) inward 4. Turn on `strict` flags one at a time, fixing errors as they surface 5. Do NOT convert everything at once Start me on the first directory.
Migrate from callbacks to promises
This legacy code uses callbacks throughout. Migration plan: 1. Identify the leaf async functions (no callers waiting on them yet) 2. Wrap or promisify them first 3. Move up the call stack, converting one layer at a time 4. Preserve error semantics (callback errors -> rejected promise) 5. Update tests Do not do it all in one PR.
Consolidate multiple databases into one
We have separate DBs for [reason]. We want to consolidate into one for [reason]. Plan: 1. Namespace tables (prefix or schema) 2. Foreign keys across old DB boundaries 3. Migration order (dependencies) 4. Cutover strategy: dual-write until consistent, then read-switch, then write-switch 5. Rollback path at each step Before starting, revisit whether consolidation is actually the right call.
Architecture
Compare architectures for a new system
I need to build [describe system]. Compare 2-3 architecture options: - Monolith / modular monolith / microservices / serverless - For each: pros, cons, cost, complexity, team-size fit - Recommend one and justify Do not default to microservices. Default to the simplest thing that works.
Design event-driven flow
This flow is currently synchronous but should be event-driven because [reason]. Design: - Event schema (type, key, payload, version) - Transport (Kafka / SQS / Pub-Sub / DB outbox pattern) - Producer changes (transactional publish? outbox?) - Consumer changes (at-least-once, dedup, retry, DLQ) - Observability (tracing across event boundaries) Before designing, confirm we actually need eventual consistency and can tolerate it.
Design a background job system
I need a background job system for [workload]. Design: - Queue: durable? priority? delayed? - Worker model: process per job, pool, fan-out - Retry policy: max attempts, backoff, DLQ - Concurrency limits (per queue, per user, global) - Idempotency (jobs may be executed twice) - Observability (job success/failure/duration metrics) Recommend an existing library over rolling your own if one fits.
Design multi-tenancy
This app needs to become multi-tenant. Choose isolation model: - Shared DB, tenant_id column - Schema per tenant - DB per tenant For the chosen model: - Query enforcement (never leak between tenants) - Migration path from current single-tenant data - Auth: how does a request identify its tenant? - Backup + noisy-neighbor concerns Recommend based on tenant count + isolation requirements.
Design feature flag system
I need feature flags. Design: - Flag types: boolean, multivariate, percentage rollout, user-list - Storage: config file / env / DB / hosted service - Evaluation: server-side / client-side / both (careful with client-side exposing all flags) - Auditing: who changed which flag when - Cleanup: how do we prevent zombie flags? enforce a TTL? Recommend a hosted service (LaunchDarkly, PostHog, Unleash, Flagsmith) vs rolling your own.
Design an API rate-limit tier system
Design tiered rate limits (free / pro / enterprise). Include: - Limit values per tier (per second, per hour, per day) - Enforcement point (edge / app / DB) - How is the caller's tier determined (API key metadata? user lookup?) - Overage handling (429? soft limit with warning?) - Documentation for customers Propose sensible defaults per tier.
How to use these
- Find a prompt matching your task
- Click Copy
- Paste into your AI IDE's chat (Cursor Chat, Claude Code, Copilot Chat, Windsurf Cascade)
- Add the code or context you want it applied to
Contributing
Have a prompt that consistently works? Email hello@devtoolsniff.com. Attribution kept.