120 ChatGPT Prompts for Software development

Getting useful output from ChatGPT comes down to one thing: the prompt. Vague inputs produce generic code, bloated explanations, and wasted back-and-forths. This guide cuts through that with 120 battle-tested ChatGPT prompts for software development, covering everything from debugging and code review to system design, documentation, and API integration. Copy them, adapt them, and ship faster.

Set up a new project scaffold

Project Setup
prompt template
Act as a senior software engineer. I want to start a new [web / mobile / backend / CLI] project using [tech stack, e.g., React + Node.js / Django / Spring Boot]. Generate a complete project scaffold that includes: Recommended folder and file structure with explanation for each directory Essential configuration files (package.json / requirements.txt / pom.xml / .env.example) Linting and formatting setup (ESLint + Prettier / Black + isort / Checkstyle) Git configuration: .gitignore, commit message convention, and branch naming strategy README template with sections: overview, prerequisites, setup, run, test, deploy A Makefile or task runner config with commands for build, test, lint, and run Prioritize developer experience and team scalability. Explain any non-obvious choices.

Write a clean REST API endpoint

Backend Development
prompt template
You are a backend engineer. I need to implement a REST API endpoint for [describe the resource and action, e.g., "creating a new user account"]. Build a production-ready endpoint that includes: Route definition with correct HTTP method and URL path following REST conventions Input validation with descriptive error messages for each field Business logic layer separated from the controller Database interaction using [ORM / raw SQL / query builder] — write parameterized queries only Proper HTTP status codes for success (201 / 200) and all failure paths (400, 401, 403, 404, 500) Consistent JSON response format: { success, data, message, errors } Unit tests covering happy path, validation failure, and database error scenarios Use [language/framework]. Follow SOLID principles and include inline comments for non-obvious logic.

Design a normalized database schema

Database Design
prompt template
Act as a database architect. I am building [describe the application, e.g., "an e-commerce platform with products, orders, and customers"]. Design a normalized relational schema that: Identifies all entities and their attributes Defines primary keys, foreign keys, and junction tables for many-to-many relationships Applies normalization up to 3NF — explain any deliberate denormalization decisions Specifies data types, constraints (NOT NULL, UNIQUE, CHECK), and default values Adds indexes for all foreign keys and expected high-frequency query columns Includes an ER diagram description (or ASCII diagram) showing all relationships Provides the full DDL SQL to create all tables Use [PostgreSQL / MySQL / SQLite]. Anticipate [expected scale, e.g., 1M rows/month] and call out any scalability considerations.

Debug a failing function

Debugging
prompt template
Act as a senior debugger. The following [language] function is producing incorrect output or throwing an error: [paste your function here] Error or unexpected behavior: [describe what's happening vs. what's expected] Input I'm testing with: [provide sample inputs] Do the following: Identify the root cause — not just the symptom Explain why the bug occurs in plain English Show the corrected function with the fix highlighted Add at least 3 test cases (edge cases included) that would catch this bug going forward List any other code smells or latent bugs you spot in the function Suggest a refactor if the logic can be simplified Do not guess — trace the execution step by step before concluding.

Write comprehensive unit tests

Testing
prompt template
You are a QA engineer and testing expert. I have the following function / class / module: [paste your code here] Write a full unit test suite in [Jest / PyTest / JUnit / RSpec] that: Tests every public method with at least one happy path test Covers all branching logic (if/else, switch, early returns) Tests boundary conditions: empty input, null/undefined, zero, max value, special characters Mocks all external dependencies (DB calls, API calls, file I/O) correctly Includes at least 2 negative tests for expected error/exception scenarios Uses descriptive test names that read as sentences: "should return X when Y" Groups tests logically using describe/context blocks Aim for 90%+ branch coverage. Explain any test you consider the most important and why.

Refactor legacy code

Code Quality
prompt template
Act as a software architect specializing in code quality. Here is a legacy [language] code block that needs to be modernized: [paste your legacy code here] Context: This code was written [X years ago] and runs in production. It has [known problems: no tests / performance issues / hard to read / tightly coupled]. Refactor it to: Apply [SOLID / DRY / KISS / YAGNI] principles — call out which ones you're applying and where Replace anti-patterns with idiomatic [language] patterns Break large functions into single-responsibility units Improve naming for all variables, functions, and parameters Add JSDoc / docstrings to all public functions Preserve 100% behavioral parity — list any assumptions you make Show a before/after diff-style comparison of the most impactful changes Do not introduce new dependencies unless clearly justified.

Implement authentication and authorization

Security
prompt template
You are a security-focused backend engineer. I need to implement auth for a [REST API / GraphQL API / web app] using [JWT / OAuth2 / session-based auth]. Build a complete auth system that includes: User registration with password hashing using bcrypt (cost factor ≥ 12) Login endpoint that returns [access token + refresh token / session cookie] JWT signing with RS256 (preferred) or HS256 — explain the tradeoff Access token expiry of 15 minutes; refresh token rotation with 7-day expiry Middleware to protect routes: verify token, extract user identity, attach to request context Role-based access control (RBAC) with at least 3 roles: admin, editor, viewer Rate limiting on login endpoint to prevent brute force Secure cookie flags (httpOnly, Secure, SameSite=Strict) if using cookies Use [language/framework]. Follow OWASP top 10 guidelines and call out any security decisions explicitly.

Optimize a slow database query

Performance
prompt template
Act as a database performance engineer. The following SQL query is running slowly on a table with [X million rows]: sql [paste your query here] Current execution time: [X seconds] Table schema: [describe relevant columns and existing indexes] Database: [PostgreSQL / MySQL / SQL Server] Do the following: Run an EXPLAIN ANALYZE interpretation — describe what each step costs Identify the performance bottlenecks: missing indexes, full table scans, N+1 patterns, inefficient joins Rewrite the query with optimizations applied Specify which indexes to create (type, columns, partial/composite) and why Estimate the performance improvement expected List 3 query patterns in this codebase I should audit for similar issues Show the original vs. optimized query side by side and explain every change made.

Build a CI/CD pipeline

DevOps
prompt template
You are a DevOps engineer. I want to set up a CI/CD pipeline for a [language/framework] application hosted on [GitHub / GitLab / Bitbucket] and deploying to [AWS / GCP / Azure / Kubernetes / Vercel]. Build a complete pipeline configuration that: Triggers on: PR open (CI only), merge to main (CI + CD), and manual deployment to production CI stage: install dependencies, lint, run unit tests, run integration tests, build artifact CD stage: build and push Docker image to [ECR / GCR / DockerHub], deploy to [environment] Uses environment-specific variables for staging vs. production (never hardcoded) Implements rollback: automatic on health check failure, manual trigger available Sends deployment notifications to [Slack / Teams / email] Caches dependencies between runs to minimize build time Output the full YAML configuration with inline comments. Flag any secrets that must be configured in the CI/CD platform.

Create a Docker containerization setup

DevOps
prompt template
Act as a containerization expert. I have a [language/framework] application that I need to containerize for [development / staging / production]. Create a complete Docker setup including: A multi-stage Dockerfile: build stage + lean production image (use Alpine or Distroless where possible) .dockerignore file — explain why each entry matters docker-compose.yml for local development with all services: app, database, cache, optional message queue Health check configuration for each service Volume mounts for development hot-reload and persistent data Non-root user setup in the container for security Environment variable handling using .env file with .env.example template Optimize for image size and startup time. Explain any layer caching strategies applied.

Design a microservices architecture

Architecture
prompt template
You are a solutions architect. I want to decompose a monolithic [describe your app] into microservices. The monolith currently handles: [list main features / modules] Expected scale: [concurrent users, requests/second, data volume] Team size: [number of developers / teams] Design a microservices architecture that: Identifies service boundaries using domain-driven design (DDD) — define each bounded context Specifies the API contract between services (REST / gRPC / events) Recommends synchronous vs. asynchronous communication per service pair and explains why Designs the event-driven backbone if applicable (Kafka / RabbitMQ / SQS) — topic/queue design Addresses cross-cutting concerns: auth, logging, tracing, rate limiting (API gateway or sidecar) Defines a data ownership model — no shared databases Provides a phased migration plan from monolith to microservices with zero downtime Include an architecture diagram description with all services, communication patterns, and data stores labeled.

Write a GraphQL schema and resolvers

API Development
prompt template
Act as a GraphQL API expert. I need to build a GraphQL API for [describe your domain, e.g., a blog platform with posts, authors, and comments]. Deliver a complete implementation that includes: Full SDL schema: all types, queries, mutations, and subscriptions with descriptions Input types with validation rules defined in schema Resolver implementations for each query and mutation using [DataLoader / batch loading] to avoid N+1 queries Authentication directive (@auth) and authorization logic in resolvers Error handling using union types (Result | Error pattern) — not generic errors Pagination on all list queries using cursor-based pagination (not offset) Example queries and mutations for each operation with expected response shapes Use [Apollo Server / Nexus / Pothos / Strawberry]. Include performance considerations for deeply nested queries.

Implement a caching strategy

Performance
prompt template
You are a backend performance engineer. My [API / application] is experiencing high latency due to expensive operations: [describe: DB queries, third-party API calls, heavy computation]. Design and implement a multi-layer caching strategy that: Identifies what to cache vs. what must always be fresh — provide decision criteria Implements in-memory caching (LRU cache) for [specific use case] Implements distributed caching with Redis: key design, TTL strategy, and eviction policy Handles cache invalidation: TTL-based, event-driven, and manual purge endpoints Adds cache-aside vs. write-through vs. write-behind — recommend the right pattern per data type Prevents cache stampede using probabilistic early expiration or locking Adds cache hit/miss metrics instrumentation Show complete code for the caching layer and explain the TTL values chosen for each data type.

Build a real-time WebSocket feature

Real-time
prompt template
Act as a real-time systems engineer. I want to add [live chat / live notifications / collaborative editing / real-time dashboard updates] to my [framework] application. Build a production-ready WebSocket implementation that: Sets up WebSocket server with connection lifecycle management (connect, message, disconnect, error) Implements rooms/channels so messages are scoped to the right users Handles authentication of WebSocket connections using the existing JWT-based auth Broadcasts events to specific users, rooms, or all connected clients as needed Implements heartbeat/ping-pong to detect and clean up stale connections Adds reconnection logic on the client side with exponential backoff Handles horizontal scaling — how to share state across multiple server instances using Redis Pub/Sub Use [Socket.io / ws / native WebSocket]. Include both server and client-side code.

Generate API documentation

Documentation
prompt template
You are a technical writer and API expert. I have the following API with these endpoints: [paste your route definitions, controller signatures, or OpenAPI partial here] Generate complete API documentation that includes: OpenAPI 3.1 YAML spec for all endpoints with full request/response schemas Description for every endpoint: purpose, who should use it, and any rate limits All request parameters: path, query, header, and body — with type, required/optional, and example values All possible response codes with schema and plain-English explanation of when each occurs Authentication section: how to obtain and pass credentials At least 2 curl examples per endpoint (success and a common failure) A Postman collection JSON ready to import Format the OpenAPI spec to be importable into Swagger UI, Redoc, or Postman without modification.

Implement error handling middleware

Backend Development
prompt template
Act as a senior backend engineer. My [framework] application has inconsistent error handling — some errors crash the server, others return unhelpful messages, and none are logged consistently. Build a centralized error handling system that: Defines a custom error class hierarchy: AppError → ValidationError, AuthError, NotFoundError, DatabaseError Includes error code, HTTP status, user-facing message, and internal debug message per error type Implements global error handling middleware that catches all unhandled errors Returns consistent JSON error response: { success: false, error: { code, message, details } } Sanitizes error messages — never expose stack traces or DB internals to clients Logs all errors with: timestamp, request ID, user ID, route, error type, stack trace Sends alerts for 5xx errors via [Slack webhook / PagerDuty / email] Show the full implementation and demonstrate how to throw and catch errors across controllers, services, and middleware.

Write a database migration

Database
prompt template
You are a database engineer. I need to make the following schema change to a production database with [X million rows] and zero-downtime requirement: Change required: [describe exactly what needs to change — add column, rename column, change type, add index, split table] Current schema: [paste relevant DDL] Deliver a safe migration plan that: Uses expand-contract (parallel change) pattern to ensure backward compatibility Writes the migration script with UP and DOWN operations Adds the new column as nullable first, then backfills data in batches of [1000–10000] rows to avoid locking Creates indexes concurrently (CONCURRENTLY keyword for PostgreSQL) Handles rollback: what to do if the migration fails halfway Includes a pre-migration checklist (backups, disk space, replication lag check) Provides estimated migration time based on table size Use [Flyway / Alembic / Liquibase / raw SQL] migration tooling.

Implement a job queue and background worker

Backend Development
prompt template
Act as a backend systems engineer. I need to offload [describe the heavy task: email sending, image processing, report generation, third-party API calls] to a background job queue. Build a complete job queue system that: Sets up [BullMQ / Celery / Sidekiq / Hangfire] with [Redis / RabbitMQ] as the broker Defines job schema with all required payload fields and their types Implements the worker with: job processing logic, success handler, and failure handler Configures retry strategy: max 3 attempts with exponential backoff (1s, 5s, 30s) Handles job timeout and marks stuck jobs as failed after [X minutes] Adds job progress tracking and status polling endpoint for the client Implements dead letter queue for permanently failed jobs with alerting Include the producer (enqueue) and consumer (process) code, plus a monitoring dashboard setup if the library supports it.

Design a rate limiting system

Security & Performance
prompt template
You are a backend engineer. I need to implement rate limiting on my [REST API / GraphQL API] to prevent abuse, protect upstream services, and ensure fair usage. Build a rate limiting system that: Implements sliding window counter algorithm using Redis (not fixed window — explain why) Applies limits at multiple levels: per IP, per authenticated user, and per API key Sets different limits per route tier: public endpoints (100 req/min), authenticated (1000 req/min), premium (10000 req/min) Returns proper HTTP 429 response with Retry-After and X-RateLimit-* headers Whitelists internal services and health check endpoints Logs rate limit violations with user/IP for abuse detection Handles distributed rate limiting correctly across multiple server instances Show the middleware code, Redis key design, and the response headers format.

Implement file upload and storage

Backend Development
prompt template
Act as a full-stack engineer. I need to implement file upload functionality for [images / documents / videos / any file type] in my [framework] application. Build a complete file handling system that: Validates file on upload: type whitelist (MIME + extension), max size [X MB], and virus scan hook Streams large files directly to [S3 / GCS / Azure Blob] without loading into memory Generates a unique, non-guessable key for each file (UUID + original name sanitized) Creates signed pre-signed URLs for secure client-side uploads (bypassing the server for large files) Generates thumbnails or previews for [images / PDFs] using [Sharp / Pillow / ImageMagick] Stores file metadata in the database: original name, size, MIME type, storage key, uploader ID Implements soft delete — marks files as deleted in DB, runs a scheduled cleanup job for actual deletion Include both the backend API and the frontend upload component with progress indicator.

Build a search feature with full-text search

Feature Development
prompt template
You are a search engineer. I want to add full-text search to my application for [describe what users are searching: products, blog posts, users, documents]. Implement a complete search system that: Evaluates [PostgreSQL full-text search / Elasticsearch / Meilisearch / Typesense] for my scale and chooses the best fit — justify the recommendation Sets up the search index with the right field mappings and analyzers for [language] Implements the search query with: fuzzy matching, typo tolerance, phrase search, and field boosting Adds filters: faceted search by [category, price range, date] with facet counts Returns results ranked by relevance with highlighted matched terms Implements autocomplete / search-as-you-type with debouncing on the frontend Handles index synchronization: update index on create, update, and delete in the DB Show indexing code, search query, and the frontend search component.

Write a CLI tool

Tooling
prompt template
Act as a developer tooling engineer. I want to build a command-line interface (CLI) tool that [describe what the tool does, e.g., "scaffolds new microservices, manages environment configs, and interacts with our internal API"]. Build a production-quality CLI that: Uses [Commander.js / Click / Cobra / Picocli] for command parsing — justify your choice Defines at least 3 subcommands with flags, options, and arguments clearly structured Validates all input with helpful, color-coded error messages Implements interactive prompts for missing required inputs (using Inquirer / Click prompts) Reads configuration from [~/.config/mytool/config.yml] and supports override via env vars Shows progress spinners for long-running operations and a success/failure summary at the end Includes --version, --help on all commands, and man page-style usage examples Package it as an npm package / pip package / single binary. Include installation instructions.

Implement logging and observability

DevOps & Observability
prompt template
You are an SRE engineer. My application has no structured logging or observability. I need to instrument it properly for production. Set up a complete observability stack that: Implements structured JSON logging with: timestamp, log level, request ID, user ID, service name, message, and metadata Adds request ID propagation across all services and log entries using middleware Integrates distributed tracing with [OpenTelemetry + Jaeger / Zipkin / DataDog] Instruments all DB queries, external API calls, and cache operations with spans Defines key metrics: request rate, error rate, p50/p95/p99 latency, queue depth — expose via [Prometheus endpoint / StatsD] Creates a Grafana dashboard JSON with the 5 most important panels for the on-call engineer Sets up alerting rules: error rate > 1%, p99 latency > 2s, service down > 30s Show the logging middleware, tracing setup, and metric instrumentation code.

Design a data access layer (DAL)

Architecture
prompt template
Act as a software architect. I need to build a clean data access layer for my [language/framework] application using [PostgreSQL / MySQL / MongoDB / DynamoDB]. Design and implement a DAL that: Defines repository interfaces: one per aggregate root / entity (e.g., UserRepository, OrderRepository) Implements concrete repository classes with full CRUD + domain-specific query methods Handles database connection pooling configuration (min, max, timeout, idle timeout) Wraps all DB errors in domain-specific errors (not raw DB exceptions in the application layer) Implements the Unit of Work pattern for transactions spanning multiple repositories Uses query builders or typed ORMs — avoids raw string SQL in application code Makes the DAL easily swappable: program to the interface, inject the implementation Show the interface, implementation, and a service class consuming the DAL correctly.

Build an OAuth2 integration

Authentication
prompt template
You are an authentication engineer. I want to add "Sign in with [Google / GitHub / Microsoft / Apple]" to my [web / mobile] application. Build a complete OAuth2 integration that: Implements the Authorization Code Flow with PKCE (required for SPAs and mobile) Builds the authorization URL with correct scopes, state parameter (CSRF protection), and nonce Handles the callback: validates state, exchanges code for tokens, and handles errors from the provider Fetches the user profile from the provider's API and maps it to your internal user model Links OAuth accounts to existing email-based accounts (account merging logic) Stores refresh tokens securely (encrypted at rest) and refreshes access tokens transparently Handles token revocation on logout and account disconnect Show server-side code for all endpoints plus the frontend redirect initiation. Include error handling for all OAuth failure modes.

Implement pagination and infinite scroll

Frontend & Backend
prompt template
Act as a full-stack engineer. I need to implement pagination on an endpoint that returns [describe the resource] with [estimated row count]. Build a complete pagination system that: Evaluates cursor-based vs. offset-based pagination for my use case — recommend the right approach Implements the backend endpoint with: page size defaulting to 20 (max 100), cursor or page parameter, and sort options Returns pagination metadata: { data, total, nextCursor, hasNextPage } or { data, page, totalPages } Implements stable sort (no skipped or duplicated rows on concurrent inserts) Builds the frontend component with: loading state, empty state, error state, and end-of-list state Implements infinite scroll using IntersectionObserver (not scroll events) with prefetch trigger at 80% scroll Handles deep linking — the URL reflects the current page or cursor so users can share/bookmark Show both the API and the frontend component code.

Write a data seeder for development

Developer Experience
prompt template
You are a developer experience engineer. I need to populate a development database with realistic test data for [describe your schema: tables/collections and their relationships]. Build a comprehensive data seeder that: Generates [X] rows per table in the correct order to satisfy foreign key constraints Uses [Faker.js / Faker (Python) / Bogus] to generate realistic field values per data type Creates deterministic data with a fixed seed so all developers get the same dataset Handles many-to-many relationships and junction tables correctly Avoids duplicate key violations on re-runs: truncate-then-seed or upsert strategy Creates specific named test fixtures: admin user, free user, premium user, banned user — for use in tests Is runnable as a single command: make seed or npm run db:seed Output the full seeder script. Include a summary of what gets created when it runs.

Implement feature flags

Engineering Practices
prompt template
Act as a platform engineer. I want to implement feature flags in my application to support [gradual rollouts / A/B testing / kill switches / beta user access]. Build a feature flag system that: Defines flags in a config file or admin UI with: flag key, description, enabled state, and rollout percentage Supports targeting rules: enable for specific user IDs, email domains, or user attributes Evaluates flags at request time with fallback to default if the flag service is unavailable Implements a lightweight SDK that checks flags in-memory (loaded at startup, refreshed every 60s) Adds flag evaluation to middleware and makes the result available throughout the request context Logs all flag evaluations for auditability and to debug unexpected behavior Integrates with [LaunchDarkly / Unleash / Flagsmith / self-hosted Redis store] — or builds a simple version from scratch Show the flag evaluation logic, targeting rule engine, and an example of guarding a new feature with a flag.

Conduct a code review

Code Quality
prompt template
You are a senior engineer conducting a formal code review. Here is the code submitted in a pull request: [paste the code to review] Context: This code [adds a new feature / fixes a bug / refactors existing logic] in a [production / internal / open-source] codebase. Review the code and provide structured feedback covering: Correctness: Are there bugs, edge cases not handled, or incorrect logic? Security: Any SQL injection, XSS, insecure deserialization, hardcoded secrets, or OWASP concerns? Performance: Any N+1 queries, memory leaks, unbounded loops, or missing indexes? Maintainability: Is the code readable, well-named, and appropriately commented? Test coverage: What is missing from tests? Are mocks used correctly? Architecture: Does it follow existing patterns? Any violations of SOLID or DRY? Blocking vs. non-blocking feedback: Label each comment as [MUST FIX] / [SUGGESTION] / [NITPICK] End with an overall verdict: Approve / Request Changes / Needs Discussion.

Build a WebSocket-based collaborative editing feature

Real-time
prompt template
Act as a real-time collaboration engineer. I want to add collaborative document editing [like Google Docs] to my application where multiple users can edit the same document simultaneously. Implement a conflict-free collaborative editing system that: Explains the choice between OT (Operational Transformation) and CRDT — recommend the right approach for my use case Implements the chosen algorithm for handling concurrent edits without conflicts Broadcasts operations via WebSocket to all connected users in real time Shows each user's cursor position in the document with their name and a unique color Handles reconnection: replays missed operations since last known state when a user reconnects Persists the document state periodically (every 30s or on disconnect) to the database Implements presence awareness: who is currently viewing/editing the document Use [Yjs / Automerge / ShareDB] and show both server and client implementation.

Generate a performance profiling report

Performance
prompt template
You are a performance engineering expert. I have a [language] application that is slow under load. I ran the following profiler output: [paste profiler results, flame graph description, or slow query log] Analyze the profiling data and provide: The top 3 bottlenecks ranked by impact (% of total time / resources consumed) Root cause analysis for each bottleneck — not just "this function is slow" but why A concrete fix for each bottleneck with expected improvement estimate Code changes needed to implement each fix How to verify the fix worked — which metric to measure and by how much it should improve Recommended profiling tools and cadence to run going forward A list of 5 proactive performance practices to prevent future regressions Be specific — reference function names, line numbers, and actual numbers from the profiler output.

Write a load testing script

Performance Testing
prompt template
Act as a performance test engineer. I need to load test my [API / service] to validate it can handle [X concurrent users / Y requests per second] before going to production. Create a complete load test suite using [k6 / Locust / Artillery / JMeter] that: Defines realistic user scenarios based on actual usage patterns: [describe the key flows] Implements [X] virtual users ramping up over [Y minutes] to the target load Includes think time between requests to simulate real user behavior Parameterizes test data (user credentials, search terms, product IDs) from a CSV or inline list Sets pass/fail thresholds: p95 latency < 500ms, error rate < 0.1%, throughput ≥ [X req/s] Produces a results report: throughput, response time distribution, error log, and bottleneck identification Includes a stress test scenario that ramps to 200% of target to find the breaking point Output the full test script plus instructions on how to run it locally and in CI.

Create an API client SDK

Developer Tooling
prompt template
You are an SDK engineer. I want to create a client SDK for my REST API in [JavaScript / Python / Go / Java] so that developers can integrate with it easily. Build a production-grade SDK that: Auto-generates typed models for all request and response schemas Implements retry logic: exponential backoff with jitter for 429 and 5xx responses (max 3 retries) Handles authentication transparently: accepts API key or OAuth token, refreshes tokens automatically Provides both promise-based and async/await interfaces (for JS/Python) Implements request timeouts with sensible defaults (30s connect, 60s read) Includes comprehensive error types: ApiError, AuthenticationError, RateLimitError, NetworkError Publishes to [npm / PyPI / pkg.go.dev] with a README showing the top 5 use cases and a quickstart Show the core HTTP client, a sample resource class (e.g., UsersClient), and end-to-end usage examples.

Implement event sourcing

Architecture
prompt template
Act as a software architect. I want to implement event sourcing for the [describe your domain, e.g., order management / account transactions / inventory] module of my application. Design and implement a complete event sourcing system that: Defines the domain events as immutable value objects with: eventType, aggregateId, version, timestamp, payload Implements the event store: append-only writes, read by aggregateId, and optimistic concurrency with version checking Builds the aggregate: loads state by replaying all events, applies new events, and emits them to the store Implements snapshots for aggregates with >100 events to avoid slow replay Projects events into read models (query-side) using [PostgreSQL / Redis / Elasticsearch] Handles event versioning: how to evolve events without breaking existing data (upcasting pattern) Provides a complete example: create order → add item → payment confirmed → order shipped — end to end Use [EventStoreDB / custom implementation]. Show the event store, aggregate, and one projection.

Implement the CQRS pattern

Architecture
prompt template
You are a solutions architect. I want to apply the Command Query Responsibility Segregation (CQRS) pattern to my [describe your domain] to improve scalability and separation of concerns. Design a CQRS implementation that: Separates the write model (commands) and read model (queries) at the code and data level Defines commands as intent objects: CreateOrder, CancelOrder, UpdateShippingAddress Implements command handlers that validate, execute business logic, and persist to the write store Defines queries as specific read request objects: GetOrderSummary, ListOrdersByCustomer Implements query handlers that read from optimized read models (denormalized for fast reads) Propagates changes from write to read model: synchronously (same transaction) or asynchronously (events) Explains when CQRS adds value vs. when it adds unnecessary complexity — and the tradeoffs for my case Show a complete end-to-end example from HTTP request → command → handler → read model update → query.

Build a multi-tenant SaaS architecture

Architecture
prompt template
Act as a SaaS architect. I am building a multi-tenant application for [describe the product] and need to decide on a tenancy model and implement tenant isolation. Design a multi-tenant architecture that: Evaluates the 3 tenancy models (shared DB, schema-per-tenant, DB-per-tenant) and recommends the right approach based on [expected tenant count, compliance requirements, customization needs] Implements tenant identification: subdomain-based, JWT claim-based, or API key header Adds tenant context middleware that extracts tenant ID and attaches it to every request Ensures all DB queries are scoped to the current tenant — no cross-tenant data leakage Implements tenant provisioning: creates the tenant record, provisions their data space, and seeds default data Handles tenant-specific configuration: feature flags, branding, limits Designs the billing model integration: how usage is tracked per tenant for metering Show the tenant middleware, query scoping strategy, and a sample onboarding flow.

Write infrastructure as code (IaC)

DevOps
prompt template
You are a DevOps engineer. I need to provision the infrastructure for a [describe the system: web app, API, data pipeline] on [AWS / GCP / Azure]. Required infrastructure: Compute: [EC2 / ECS / EKS / Cloud Run / Lambda] Database: [RDS PostgreSQL / Cloud SQL / Aurora / DynamoDB] Cache: [ElastiCache Redis / Memorystore] CDN: [CloudFront / Cloud CDN] Networking: [VPC, subnets, security groups, NAT gateway] Write Terraform (or Pulumi) configuration that: Provisions all resources with least-privilege IAM roles Separates environments using [workspaces / modules]: dev, staging, production Stores Terraform state in [S3 + DynamoDB locking / GCS] Uses variables for all environment-specific values — no hardcoded ARNs or IDs Includes resource tagging: environment, project, owner, cost center Outputs all critical values: endpoint URLs, ARNs, connection strings (use Secrets Manager for sensitive ones) Provide the full .tf files and a README on how to init, plan, and apply.

Design a webhook system

Backend Development
prompt template
Act as a backend engineer. I want to implement a webhook system so that my platform can notify external systems when [describe events: order placed, payment completed, user registered]. Build a production-ready webhook system that: Allows customers to register webhook endpoints via API: URL, secret, and event type subscriptions Delivers webhooks asynchronously via a job queue — never in the request path Signs each payload using HMAC-SHA256 with the customer's secret and sends the signature in a header Retries failed deliveries: max 5 attempts with exponential backoff (1m, 5m, 30m, 2h, 24h) Records every delivery attempt: timestamp, HTTP status, response body, and latency Provides a dashboard endpoint for customers to view delivery history and manually retry failed events Implements a test mode: customers can send a test event to verify their endpoint is working Show the registration API, delivery worker, signature verification guide for customers, and the retry logic.

Implement API versioning

API Design
prompt template
You are an API design expert. My REST API has been in production for [X months] and I need to introduce breaking changes while keeping existing clients working. Design and implement an API versioning strategy that: Evaluates URL versioning (/v1/), header versioning (Accept: application/vnd.api+json;version=2), and query param versioning — recommend the best fit and justify Implements the chosen strategy with routing that maps versions to the right controller/handler Defines a deprecation policy: minimum [X months] notice, deprecation header in responses, sunset date Handles shared code between versions: how to avoid duplicating business logic Implements a version negotiation middleware that selects the right version or returns 400 for unsupported versions Documents the migration guide from v1 to v2 for each breaking change Adds version metrics: track usage per version to know when it's safe to retire an old version Show the routing config, middleware, and a concrete example of migrating one endpoint from v1 to v2.

Build a notification system

Feature Development
prompt template
Act as a backend engineer. I need to build a multi-channel notification system for my application that sends [email, push, SMS, in-app] notifications. Design a notification system that: Defines a unified notification interface with: recipient, channel, template ID, variables, and priority Routes notifications to the right channel based on user preferences and notification type Integrates with: [SendGrid / SES] for email, [FCM / APNs] for push, [Twilio] for SMS Implements template rendering with variable substitution and HTML/plain text variants for email Queues all notifications via a job queue with channel-specific workers Handles delivery failures: retry for transient errors, fallback channel if primary fails Tracks delivery status per notification: sent, delivered, opened, clicked, failed Show the notification service interface, the email worker, and the user preference API.

Design a secrets management strategy

Security
prompt template
You are a security engineer. My application currently has secrets [hardcoded in config files / in environment variables in .env files / committed to the repo] and needs to be secured properly. Implement a proper secrets management strategy that: Audits and catalogs all current secrets: DB passwords, API keys, JWT signing keys, OAuth secrets Migrates all secrets to [HashiCorp Vault / AWS Secrets Manager / GCP Secret Manager / Azure Key Vault] Implements dynamic secrets for database credentials: short-lived credentials generated per service Rotates all secrets without downtime: blue-green rotation strategy for each secret type Injects secrets into the application at runtime (not baked into images or config files) Implements least-privilege access: each service can only read the specific secrets it needs Adds secret access audit logging and alerts for unauthorized access attempts Show the Vault/Secrets Manager setup, the injection mechanism, and the rotation script for one credential type.

Implement data encryption

Security
prompt template
Act as a security engineer. I need to encrypt sensitive data in my application: [list sensitive fields: SSNs, credit card numbers, health records, PII]. Design a field-level encryption system that: Chooses the right encryption approach: AES-256-GCM for data at rest, TLS for data in transit — explain when each applies Implements transparent field-level encryption: encrypts before write, decrypts after read in the data layer Manages encryption keys using [KMS / HSM / Vault] — never stores keys alongside data Implements key rotation: re-encrypts data with new key without downtime Uses envelope encryption: data encrypted with a data key, data key encrypted with a master key Handles searchable encryption where needed (blind indexing or order-preserving encryption with tradeoff explanation) Adds tamper detection using MAC or digital signatures on sensitive records Show the encryption/decryption utilities, key management calls, and the repository layer implementing transparent encryption.

Build a plugin/extension architecture

Architecture
prompt template
You are a software architect. I want to make my [application type] extensible via a plugin system so that [internal teams / third-party developers] can add new capabilities without modifying core code. Design a plugin architecture that: Defines the plugin interface: required methods (initialize, teardown), lifecycle hooks, and metadata schema Implements a plugin registry: discovers, loads, and validates plugins at startup Uses dependency injection to provide plugins with sandboxed access to core services Implements an event/hook system: plugins can subscribe to and emit named events Enforces plugin isolation: a crashing plugin should not bring down the core application Handles plugin versioning and compatibility checking against the core API version Provides a starter plugin template and developer documentation Show the plugin interface, the registry implementation, an example plugin, and how the core application calls plugins at lifecycle events.

Implement a state machine

Feature Development
prompt template
Act as a software engineer. I have a domain entity that has complex state transitions: [describe the entity and its states, e.g., "an order that can be: draft → submitted → approved → shipped → delivered → cancelled"]. Implement a formal state machine that: Defines all states as an enum or constants Defines all valid transitions as a transition table: { from, event, to, guard, action } Implements guard conditions that prevent invalid transitions (e.g., can't ship an unpaid order) Executes side effects (actions) on transitions: send notification, update audit log, call external API Throws a clear error for any attempted invalid transition Persists the current state to the database and records all transitions in a state history table Provides a method to visualize the state machine as a diagram (Mermaid or Graphviz notation) Use [XState / python-statemachine / Spring State Machine / custom implementation]. Show the full machine definition and a usage example.

Design an idempotent API

API Design
prompt template
You are an API design expert. I need my [payment processing / order creation / resource provisioning] API endpoints to be idempotent so that duplicate requests (retries, network failures) don't cause duplicate operations. Implement idempotency for my API that: Accepts an Idempotency-Key header on all mutating endpoints (POST, PATCH) Stores the idempotency key + response in a cache (Redis) with a 24-hour TTL On duplicate request: returns the cached response without re-executing the business logic Handles concurrent duplicate requests: uses Redis locking to prevent race conditions Scopes idempotency keys per user or API key — keys are not global Returns the same HTTP status and response body for both the original and duplicate requests Documents the idempotency behavior in the API docs with retry guidance for clients Show the idempotency middleware, the Redis storage pattern, and a test demonstrating the behavior.

Build a scheduled jobs system

Backend Development
prompt template
Act as a backend engineer. I need to run scheduled background jobs: [list your jobs with their schedules, e.g., "generate daily reports at 2AM, clean up expired sessions every hour, send weekly digest emails every Monday 9AM"]. Build a robust scheduled job system that: Uses [node-cron / APScheduler / Quartz / Sidekiq Cron] to define all jobs as code (not DB config) Ensures each job runs exactly once in a distributed environment using [Redis lock / DB-level locking] Implements job observability: logs start time, end time, duration, and outcome for every run Handles job failure: catches errors, logs them, and alerts on repeated failures Supports manual trigger: an admin endpoint to fire any scheduled job on demand Implements graceful shutdown: running jobs complete before the process exits Provides a job history UI or log query to audit past runs Show the job definitions, the distributed lock implementation, and the failure alerting integration.

Implement a bulk data import feature

Feature Development
prompt template
You are a full-stack engineer. I need to let users bulk import [describe data: users, products, transactions] from a CSV or Excel file. Build a complete bulk import system that: Accepts file upload via API: validate file type and size before processing Parses CSV/XLSX and maps columns to internal schema — supports flexible column ordering Validates every row: collect all errors (not just the first), report row number and field name per error Processes valid rows in batches of 500 using bulk insert (not row-by-row) for performance Reports progress in real time via WebSocket or SSE: rows processed / total, errors so far Generates a results report downloadable as CSV: success rows, error rows with error descriptions Handles large files (>100k rows) without timing out: processes asynchronously as a background job Show the upload endpoint, the parser and validator, the batch insert logic, and the error report generator.

Write a technical architecture decision record (ADR)

Documentation
prompt template
Act as a staff engineer. I need to document an architectural decision I made: [describe the decision, e.g., "switching from a monolith to microservices" / "choosing PostgreSQL over MongoDB" / "adopting event-driven architecture"]. Write a formal Architecture Decision Record (ADR) that includes: Title: ADR-[number]: [short imperative title] Status: [Proposed / Accepted / Deprecated / Superseded by ADR-X] Context: the forces at play — the problem, constraints, and why a decision was needed Decision: what was decided in a single clear statement Alternatives considered: at least 2 other options with pros and cons of each Consequences: both positive outcomes and accepted tradeoffs / risks Implementation notes: key steps needed to execute this decision Write in a neutral, factual tone. This document should be readable by engineers who join the team in 2 years and need to understand why this choice was made.

Generate environment configuration management

Developer Experience
prompt template
You are a backend engineer. My application runs across [dev / staging / production] environments and I need a clean, secure, and maintainable approach to environment-specific configuration. Build a configuration management system that: Defines all config values in a typed config schema with descriptions and defaults Loads values from environment variables — no config files committed with secrets Validates all required values at startup — fails fast with clear error messages if any are missing Provides typed access to config values throughout the app (no raw process.env.X calls in business logic) Supports local development via .env file with .env.example as documentation Handles different value types: strings, numbers, booleans, URLs, durations, arrays Documents every config variable: what it does, required/optional, and example value Show the config schema, the loader, the validator, and an example of using the config in a service.

Build a data pipeline

Data Engineering
prompt template
Act as a data engineer. I need to build a pipeline that [describe what data flows where: "extracts user activity from PostgreSQL, transforms it, and loads it into a data warehouse for analytics"]. Design and implement a complete ETL/ELT pipeline that: Extracts data from [source: PostgreSQL / REST API / S3 / Kafka] using incremental extraction (watermark-based, not full-table) Transforms the data: cleaning, type casting, deduplication, business rule application — each transform as a pure function Loads data to [destination: BigQuery / Snowflake / Redshift / ClickHouse] using bulk load for efficiency Schedules the pipeline to run [frequency] and handles late-arriving data correctly Implements idempotent runs: re-running the same pipeline window produces the same output Adds data quality checks: null rate, row count reconciliation, schema drift detection Alerts on failures and data quality failures via [Slack / PagerDuty] Use [dbt / Apache Airflow / Prefect / Dagster / Luigi]. Show the pipeline definition, transforms, and quality checks.

Implement caching with cache invalidation

Performance
prompt template
You are a senior engineer. I need to cache [describe what: user profiles, product catalog, computed recommendations] in my application, but I'm struggling with cache invalidation — I keep serving stale data. Build a robust caching layer with proper invalidation that: Identifies the exact staleness tolerance for each data type — TTL strategy derived from business requirements Implements tag-based invalidation: group cache keys by entity type so invalidating an entity clears all related keys Uses Redis with the right data structures: Strings for simple values, Hashes for structured objects, Sorted Sets for ranked lists Implements cache warming: pre-populates cache on startup or after invalidation for critical paths Handles thundering herd on cache miss: uses probabilistic early expiration or a single-flight pattern Adds cache metrics: hit rate, miss rate, eviction count — alert if hit rate drops below [X%] Documents cache key naming convention: {prefix}:{entity}:{id}:{variant} Show the cache service, the invalidation logic, and integration into the repository layer.

Design an API gateway

Architecture
prompt template
Act as an infrastructure architect. I need to set up an API gateway in front of my [number] microservices to handle cross-cutting concerns. Design and configure an API gateway ([Kong / AWS API Gateway / Nginx / Traefik / custom]) that: Routes requests to the correct upstream service based on path prefix or subdomain Handles authentication and authorization: validates JWTs, rejects unauthenticated requests before they reach services Implements rate limiting per client (IP or API key) with configurable limits per route Transforms requests and responses: adds correlation IDs, normalizes error formats, strips internal headers Handles SSL termination, HTTP/2, and keep-alive configuration Implements circuit breaker: stops routing to an unhealthy upstream after [N] failures, probes for recovery Produces access logs in structured JSON format and exports metrics to Prometheus Show the full gateway configuration, the routing rules, and the plugin/middleware stack.

Write integration tests

Testing
prompt template
You are a QA engineer. I need integration tests for my [API / service] that test the full stack — not just unit behavior, but how the system behaves against real dependencies. Write a complete integration test suite that: Spins up real dependencies using [Testcontainers / Docker Compose / in-memory test DB] before tests run Tests full request-to-database flows: HTTP request → controller → service → DB → response Covers critical user journeys: [list your top 3-5 flows, e.g., user registration, checkout, password reset] Validates the exact HTTP status, response shape, and database state after each operation Tests failure scenarios: DB down, third-party API timeout, invalid auth — using dependency mocks/stubs Cleans up test data between tests using transactions that rollback or truncate-and-reseed Runs in CI in under 2 minutes — parallelizes test files and shares the DB container across the suite Show the test setup, at least 2 complete integration test scenarios, and the CI configuration to run them.

Build an admin dashboard backend

Feature Development
prompt template
Act as a full-stack engineer. I need to build a backend for an admin dashboard that gives internal staff visibility and control over [describe: user management, order management, content moderation, system health]. Build a secure admin backend that: Requires a separate admin authentication flow: admin accounts with MFA required, stored separately from regular users Implements admin-specific RBAC: super admin, support agent, read-only analyst — with permissions per resource Provides audit logging for every admin action: who did what, to which resource, when — immutable log Builds search and filtering endpoints for [users / orders / content]: full-text search, date range, status filter, export to CSV Implements bulk actions: bulk ban, bulk email, bulk tag with confirmation step Adds admin impersonation: admin can view the app as a specific user (with audit log entry) Rate limits and IP-restricts all admin endpoints — admin API should not be publicly exposed Show the admin auth flow, permission middleware, audit log schema, and one complete admin resource CRUD module.

Implement a circuit breaker

Resilience
prompt template
You are a resilience engineering expert. My service calls [external APIs / downstream microservices] and when they go down, it causes cascading failures in my system. Implement a circuit breaker pattern that: Tracks success and failure counts in a sliding window (last 60 seconds or last 100 calls) Opens the circuit when error rate exceeds [50%] — stops calling the downstream and returns a fallback response immediately Implements half-open state: after [30 seconds], allows 1 probe request through to test recovery Closes the circuit on successful probe; re-opens immediately on probe failure Provides a fallback response for each protected call: [cached result / default value / graceful error] Exposes circuit state metrics: open/closed/half-open, error rate, trip count Logs all state transitions with timestamp and reason Use [resilience4j / polly / pybreaker / custom implementation]. Show the circuit breaker wrapper and how it's applied to external API calls.

Design a GDPR-compliant data management system

Compliance & Security
prompt template
Act as a compliance engineer. My application stores EU user data and needs to be GDPR-compliant. I currently have no proper data management for user rights. Build a GDPR compliance system that implements: Right to Access: endpoint to export all data held about a user in a machine-readable format (JSON / CSV) Right to Erasure: endpoint to delete or anonymize all user data across all tables and data stores Right to Rectification: endpoint to update inaccurate personal data Consent management: record consent with timestamp, version, and specific purposes consented to Data retention policies: automatically delete or anonymize records older than the defined retention period via scheduled job Data subject request tracking: log all data rights requests with status, requester, and completion time Privacy by design: identify all PII fields in your schema, document data flows, and implement data minimization Show the erasure implementation (hard delete vs. anonymization decision), the consent schema, and the retention job.

Build a developer portal

Developer Experience
prompt template
You are a developer experience (DX) engineer. I want to build a developer portal for my API platform so external developers can discover, try, and integrate with my APIs easily. Design a developer portal that includes: API catalog: searchable list of all APIs with name, description, version, and status Interactive API reference: renders OpenAPI spec using [Swagger UI / Redoc / Scalar] with live try-it-out functionality Authentication: developers self-register, get API keys, and manage them via a self-service UI Usage dashboard: API call count, error rate, and latency charts per developer/key Getting started guide: code samples in [5 languages] for the top 3 API use cases SDK downloads: auto-generated SDK packages for [JavaScript, Python, Go] with changelogs Changelog and deprecation notices: versioned release notes with migration guides Outline the tech stack, CMS strategy for documentation, and the key pages/components to build first.

Implement a distributed lock

Concurrency
prompt template
Act as a backend engineer. I have a distributed system with multiple instances where I need to ensure [describe the critical section: "only one instance processes a cron job at a time" / "inventory is not oversold" / "payment is processed exactly once"]. Implement a distributed locking mechanism that: Uses [Redis SETNX + expiry / Redlock / ZooKeeper / database advisory lock] — recommend and justify the choice Acquires the lock with a unique owner token (prevents a lock from being released by the wrong process) Sets a lock TTL that is longer than the expected critical section duration — explains the calculation Implements lock extension (renewal) for long-running operations to prevent premature expiry Releases the lock using a Lua script to ensure atomicity (check owner + delete in one operation) Handles the case where the lock holder crashes: TTL ensures eventual release, with dead-letter handling Wraps the locking logic in a context manager / decorator for clean usage Show the lock implementation, the usage pattern in the critical section, and how to test it for correctness.

Write a memory leak debugging guide

Debugging
prompt template
You are a performance engineer. My [Node.js / Python / Java / Go] application is experiencing a memory leak — memory grows continuously and the service restarts every [X hours]. Guide me through diagnosing and fixing the memory leak: Instrument the application to capture a heap snapshot / memory profile at 10-minute intervals Analyze the snapshots: identify objects that are growing unboundedly, their retainer chain, and the root reference keeping them alive List the 5 most common causes of memory leaks in [language/runtime] and which ones match my profile Show the specific code pattern for each cause and its correct implementation (event listeners not removed, closures capturing large objects, cache without eviction, etc.) Implement the fix for the identified cause with before/after code Add memory monitoring: track heap usage over time, alert if it grows by [X MB] per hour Add a test to prevent regression: a test that allocates, processes, and verifies memory is released

Implement a health check system

DevOps
prompt template
Act as a reliability engineer. I need to implement health check endpoints for my microservices that give orchestrators and monitoring systems accurate visibility into service health. Build a comprehensive health check system that: Implements two endpoints: /health/live (is the process alive) and /health/ready (is the service ready to serve traffic) Liveness check: only returns unhealthy if the process is stuck or in an unrecoverable state — NOT if a dependency is down Readiness check: verifies all required dependencies are reachable: DB connection, cache ping, downstream service, required config loaded Returns structured JSON: { status, version, uptime, checks: { db, cache, queue } } with each component's status and latency Implements a degraded state: service is alive and serving cached data but not all features are available Caches health check results for 5 seconds to prevent dependency overload from frequent polling Kubernetes-ready: specifies the correct liveness, readiness, and startup probe configuration in YAML

Generate a monorepo setup

Developer Experience
prompt template
You are a developer tooling engineer. I want to migrate my separate repos [list your packages: frontend, backend API, shared types, mobile app, CLI tool] into a monorepo. Design and set up a monorepo using [Turborepo / Nx / Lerna + Yarn Workspaces / Bazel] that: Defines the workspace structure with packages clearly separated by type: apps/, packages/, tools/ Shares code between packages: a common types package, a shared UI component library, a utility functions package Implements incremental builds: only rebuilds packages affected by a change Runs tasks (build, test, lint) in the correct dependency order and in parallel where safe Configures import paths so packages import each other using workspace aliases (e.g., @myco/shared) Sets up per-package versioning or release-all versioning (explain the tradeoff and recommend one) Provides CI configuration that runs only the affected package pipelines on each PR Show the workspace config, the package.json structure, and the task pipeline definition.

Build a data validation library

Feature Development
prompt template
Act as a software engineer. I need a robust data validation library [or implementation using an existing one like Zod / Pydantic / Joi / Yup] for validating [describe your data: user input, API payloads, config files, external API responses]. Build a validation system that: Defines schemas for all major data types in the application Validates primitive types, nested objects, arrays, optional fields, and union types Provides meaningful error messages: field path + human-readable description of what's wrong Collects all validation errors in one pass — not just the first failure Supports custom validators for business rules: unique email, valid discount code, date range logic Transforms and sanitizes data on parse: trim strings, normalize emails to lowercase, parse date strings to Date objects Is reusable: schema definitions are shared between server-side validation and client-side form validation Show schema definitions for at least 3 real entities, the validation call, and error message formatting.

Design a content delivery strategy

Performance
prompt template
You are a performance engineer. I need to optimize how my application serves static assets and dynamic content to global users to minimize latency and infrastructure cost. Design a content delivery strategy that: Identifies what should be served via CDN vs. what must be origin-served — with clear criteria Configures [CloudFront / Cloudflare / Fastly / Akamai] with correct Cache-Control headers per asset type: immutable for versioned assets, short TTL for HTML, no-cache for API responses Implements asset fingerprinting (content hash in filename) to enable safe long-term caching Configures CDN edge caching for [SSR / ISR / dynamic pages] where applicable Sets up cache purging: on deploy, purge HTML and API cache; never purge versioned assets Implements image optimization at the edge or origin: WebP/AVIF conversion, responsive srcset, lazy loading Measures the impact: define which Core Web Vitals metrics to track and what target values to aim for

Build an OpenAPI-first API

API Design
prompt template
Act as an API architect. I want to adopt an API-first development approach where I define the OpenAPI spec first, then generate code from it. Set up a complete API-first workflow that: Writes the full OpenAPI 3.1 spec for [describe your API domain] with all paths, schemas, and examples Configures code generation using [OpenAPI Generator / Speakeasy / oapi-codegen] to produce: server stubs in [language], client SDKs in [2 languages], and TypeScript types Sets up spec linting using [Spectral] to enforce style rules: no generic descriptions, all schemas named, no inline schemas in paths Implements contract testing: verifies the running server matches the spec on every build Generates interactive documentation that auto-updates when the spec changes Defines a governance process: how spec changes are reviewed, who can approve breaking changes Provides a mock server from the spec so frontend can develop before the backend is built Show the spec structure, the codegen config, and the contract test setup.

Implement retry logic

Resilience
prompt template
You are a reliability engineer. My application makes calls to [external APIs / databases / message queues] that sometimes fail transiently. I need robust retry logic to handle these failures gracefully. Implement a comprehensive retry system that: Distinguishes retryable errors (transient: timeouts, 429, 503) from non-retryable (permanent: 400, 404, 401) — provide the classification logic Implements exponential backoff: base delay [100ms], multiplier [2x], max delay [30s] Adds jitter to prevent thundering herd: full jitter or decorrelated jitter — explain the choice Sets a maximum retry count [3] and a total timeout budget [10s] — stops whichever is reached first Logs each retry attempt: attempt number, delay, error, next retry time Implements a retry budget for the overall service: if retry rate exceeds [X%] of total requests, stop retrying to protect downstream Wraps retryable operations in a reusable decorator/higher-order function so it's not duplicated per call site Show the retry implementation, the backoff calculation, and examples of wrapping a DB call and an HTTP call.

Build a reporting module

Feature Development
prompt template
Act as a full-stack engineer. I need to build a reporting module for my application that generates [describe report types: financial summaries, user activity reports, operational dashboards] for [daily / weekly / monthly] periods. Build a complete reporting system that: Queries pre-aggregated data (not live transactional DB) for fast report generation Implements a report definition schema: name, description, parameters (date range, filters), and output format Generates reports in multiple formats: PDF, Excel, CSV — using the same data source Schedules automated report generation and delivery via email to configured recipients Implements on-demand report generation via API with progress tracking for long-running reports Caches generated reports: same parameters within [X hours] returns cached file instead of regenerating Provides a report history UI: list of past reports, status (generating/ready/failed), and download links Show the report generation service, the PDF/Excel export code, and the scheduling configuration.

Design a testing pyramid

Testing
prompt template
You are a QA architect. My team's test suite is slow, flaky, and has low confidence. I need to redesign our testing strategy. Design a complete testing strategy that: Maps out the testing pyramid for my [type of application]: recommended ratio of unit, integration, E2E, and contract tests Defines what belongs in each layer and what definitely should NOT be in E2E tests Audits the current test suite — identify which tests are testing the wrong layer Sets standards for test quality: naming conventions, one assertion per test rule, test data management Configures test parallelization to hit a target suite runtime of under [5 minutes] in CI Implements mutation testing using [Stryker / Pitest] to validate test suite effectiveness Defines a test coverage policy: minimum branch coverage [80%], fail CI if coverage drops Provide the testing pyramid diagram, layer definitions, and the tooling stack for each layer.

Implement audit logging

Compliance & Security
prompt template
Act as a security engineer. I need to implement audit logging for my application to track who did what, when, and to which data — for compliance ([SOC 2 / HIPAA / PCI DSS / ISO 27001]) and security investigations. Build an audit logging system that: Captures all data-modifying operations: create, update, delete for sensitive resources Logs: who (user ID, IP, user agent), what (action type, resource type, resource ID), when (timestamp with timezone), and the before/after state for updates Writes audit logs to an append-only store: never update or delete audit records (use a separate DB or table) Implements log integrity: hash chaining so tampering with a log entry is detectable Indexes logs by: user, resource type + ID, and timestamp for efficient querying Provides an admin search UI and export feature for audit log review Defines retention policy: retain audit logs for [7 years] per compliance requirement Show the audit log schema, the middleware that captures events, and the log integrity mechanism.

Build a payment integration

Feature Development
prompt template
You are a backend engineer. I need to integrate [Stripe / PayPal / Braintree / Adyen] into my application to accept [one-time payments / subscriptions / marketplace payouts]. Build a production-ready payment integration that: Implements the correct payment flow: client creates payment intent → server confirms → webhook confirms payment Never stores raw card data — all sensitive data handled by the payment provider's SDK Implements idempotency keys on all payment API calls to prevent duplicate charges Handles all webhook events: payment succeeded, payment failed, subscription renewed, chargeback created Validates webhook signatures before processing any event Implements the reconciliation flow: match payment provider records with internal order records daily Handles refunds, partial refunds, and dispute (chargeback) workflows Show the payment intent creation, the webhook handler with signature validation, and the reconciliation job.

Implement a search autocomplete

Feature Development
prompt template
Act as a frontend and backend engineer. I need to implement search autocomplete for [describe what users search: products, users, articles] with fast, relevant suggestions as the user types. Build a complete autocomplete system that: Implements debouncing on the frontend: wait [300ms] after the last keystroke before calling the API Cancels in-flight requests when a new keystroke arrives (AbortController / CancelToken) Backend endpoint returns suggestions in under [100ms] for a good UX — uses a dedicated index, not a full DB scan Indexes suggestion candidates using [Trie / inverted index / Elasticsearch completion suggester / Redis Search] Returns ranked results: exact prefix match first, then fuzzy matches, ranked by [popularity / recency / relevance score] Highlights the matched portion of each suggestion in the response Handles keyboard navigation: arrow keys to move through suggestions, Enter to select, Escape to close Show the frontend component, the debounce logic, the backend endpoint, and the indexing strategy.

Design a permission system

Architecture
prompt template
You are a software architect. I need to design a flexible permission system for my application that goes beyond simple role-based access control to support [resource-level permissions / attribute-based access / delegated access]. Design a permission system that: Evaluates RBAC vs. ABAC vs. ReBAC for my use case — recommends the right model and explains why Models permissions as: action (read, write, delete, share) on resource type (document, project, user) with optional conditions (own resources only, within same organization) Defines how roles bundle permissions and how roles are assigned to users Implements permission checking as a centralized function: can(user, action, resource) → boolean Caches permission decisions for the duration of a request to avoid repeated DB lookups Supports permission inheritance: org admin inherits all project admin permissions Provides a permission debugging tool: explain why a user can or cannot do a specific action Show the permission schema, the can() implementation, and how it's used in API route guards.

Build an A/B testing framework

Engineering Practices
prompt template
Act as a product engineer. I want to run A/B tests on [UI components / feature behaviors / pricing / onboarding flows] to make data-driven product decisions. Build an A/B testing framework that: Assigns users to variants consistently: the same user always sees the same variant across sessions Uses a hashing function on user ID + experiment ID for variant assignment — no DB round trip needed Supports traffic splits: 50/50, 90/10, or multi-variant splits — configurable per experiment Logs exposure events: which variant was shown to which user, at what time, in which context Integrates with [analytics platform: Mixpanel / Amplitude / Segment / custom] to track conversion events per variant Provides a statistical significance calculator: run a two-proportion z-test to determine if the winner is real Implements guardrail metrics: auto-stop the experiment if [error rate / page load time / revenue per user] degrades beyond a threshold Show the assignment logic, exposure logging, and the significance test calculation.

Implement soft deletes

Database
prompt template
You are a backend engineer. I want to implement soft deletes in my application so that deleted records are retained for [audit purposes / data recovery / GDPR compliance / referential integrity]. Implement soft delete that: Adds a deleted_at nullable timestamp column (and optionally deleted_by) to all relevant tables Creates a global query scope that automatically filters out soft-deleted records from all queries Implements restore functionality: unset deleted_at to recover a record Handles cascading soft deletes: deleting a parent should soft-delete its children Implements hard delete (physical removal) for GDPR erasure requests that bypasses the soft delete filter Adds a unique constraint workaround: email must be unique among non-deleted users, not globally unique Creates a cleanup job that permanently deletes records soft-deleted more than [90 days] ago Show the migration, the query scope implementation, and the restore and hard delete endpoints.

Generate a system design interview answer

Architecture
prompt template
Act as a senior staff engineer. I have a system design interview question: "Design [system: Twitter / YouTube / Uber / Slack / a URL shortener / a distributed cache]." Give a structured system design answer that covers: Requirements clarification: functional requirements, non-functional requirements (scale, latency, availability), and explicit out-of-scope decisions Scale estimation: DAU, requests/second, storage per year — back-of-envelope calculation High-level architecture: major components and how data flows between them Database design: schema for the core entities, choice of DB type and justification API design: the 3-5 most important endpoints with request/response format Deep dive on the hardest component: [the feed generation / the video transcoding pipeline / the matching algorithm / the message delivery system] Bottlenecks and mitigations: where the system breaks at scale and how to fix each one Structure the answer as you would present it on a whiteboard in 45 minutes.

Write a deployment runbook

DevOps
prompt template
You are a senior engineer. I need a deployment runbook for [describe your system] so that any engineer on the team can safely deploy to production. Create a complete deployment runbook that includes: Prerequisites checklist: who can deploy, required access/permissions, required tools installed, time restrictions (no deploys on Fridays after 3PM) Pre-deployment steps: run final tests, check monitoring dashboards for baseline metrics, notify stakeholders in [Slack channel] Deployment procedure: exact commands or UI steps, in order, with expected output for each Verification steps: how to confirm the deployment succeeded — health check URL, smoke test commands, metric check Rollback procedure: exact steps to revert, how long rollback typically takes, how to confirm rollback succeeded Known issues and workarounds: [list any gotchas discovered from past deployments] Escalation contacts: who to call if the runbook fails and the deployment can't proceed Format as a numbered checklist that an engineer can follow step by step during an incident.

Build a tenant onboarding automation

Feature Development
prompt template
Act as a backend engineer. I need to automate the onboarding of new customers to my SaaS platform so they can be fully set up within [60 seconds] of signing up. Build a tenant onboarding automation that: Triggers on signup completion (webhook or event from auth system) Provisions tenant resources in order: create DB schema / namespace, seed default data, create admin user, assign default subscription plan Runs as a background job with status tracking: the signup API returns immediately, onboarding completes asynchronously Sends a welcome email with login credentials and getting started link once onboarding completes Handles partial failures: if any step fails, logs the failure, triggers an alert, and provides a manual retry endpoint Is idempotent: re-running the onboarding job for the same tenant is safe — skips already-completed steps Tracks onboarding duration and success rate as metrics — alert if average duration exceeds [2 minutes] Show the job definition, each provisioning step, the error handling, and the completion event.

Implement a GraphQL subscription

Real-time
prompt template
You are a GraphQL engineer. I need to add real-time updates to my GraphQL API using subscriptions for [describe the use case: live auction bids, order status updates, collaborative whiteboard changes]. Implement GraphQL subscriptions that: Defines the subscription type in the schema with the correct event payload type Sets up the WebSocket server alongside the HTTP server using [graphql-ws protocol] — not the deprecated subscriptions-transport-ws Implements the publish/subscribe system using [Redis Pub/Sub / EventEmitter] for multi-server support Authenticates WebSocket connections using the connectionParams passed on connect Scopes subscription events to the correct user: users only receive events relevant to their data Handles subscription lifecycle: memory cleanup on client disconnect, prevent event accumulation Tests the subscription using a WebSocket client test in the integration test suite Show the schema definition, the resolver with pub/sub, the server setup, and a subscription usage example from the client.

Design a disaster recovery plan

DevOps
prompt template
Act as an SRE engineer. I need to design a disaster recovery plan for my [describe the system] to meet these requirements: RPO [4 hours], RTO [1 hour]. Create a disaster recovery plan that: Identifies all failure scenarios: single AZ failure, full region failure, database corruption, accidental data deletion, security breach Maps each scenario to recovery steps and estimated recovery time Defines the backup strategy: what is backed up, frequency, retention, and storage location (different region) Implements automated failover for database: [RDS Multi-AZ / Aurora Global / PostgreSQL streaming replication] Provides runbooks for each failure scenario: step-by-step recovery commands with expected output Defines the DR testing schedule: full DR drill every [6 months], partial test monthly Establishes communication plan: who to notify, in what order, with what information during an incident Validate that the plan meets the RPO and RTO requirements for each failure scenario.

Build a changelog generator

Developer Tooling
prompt template
You are a developer experience engineer. I want to automate changelog generation from my git commits so that releases are documented consistently without manual effort. Build an automated changelog system that: Enforces Conventional Commits format via a git hook (commitlint): feat, fix, chore, docs, perf, refactor, BREAKING CHANGE Generates a CHANGELOG.md from commits since the last tag, grouped by: Breaking Changes, Features, Bug Fixes, Performance Auto-increments semantic version: major for BREAKING CHANGE, minor for feat, patch for fix Creates a GitHub / GitLab release with the changelog as the release body and the correct tag Includes migration notes for breaking changes: extracts the BREAKING CHANGE footer from commits Generates a version bump commit + tag in CI — no manual version bumping in package.json Publishes a "What's New" Slack message summarizing the release to the team channel Use [standard-version / semantic-release / release-please]. Show the full CI pipeline step, commitlint config, and a sample generated changelog.

Write a code generator

Developer Tooling
prompt template
Act as a developer tooling engineer. I need a code generator that scaffolds [describe what it generates: a new API resource, a new React component, a new database migration] to enforce consistency across the codebase. Build a code generator (using [Plop / Hygen / Yeoman / custom script]) that: Prompts the developer for inputs: [name, type, fields, options] — with validation on each input Generates all required files from templates: [list the files, e.g., controller, service, repository, migration, test file, API spec update] Uses the provided name to derive related names correctly: PascalCase for class names, snake_case for DB columns, kebab-case for file names Inserts generated routes or exports into existing index files — no manual registration needed Runs prettier/black on generated files so they match the project's code style Prints a summary of all created/modified files with next steps for the developer Is runnable as: npm run generate:resource or make generate Show the template files, the generator config, and a before/after example of the generated code.

Implement dependency injection

Architecture
prompt template
You are a software architect. My codebase has tightly coupled classes that instantiate their own dependencies, making unit testing and swapping implementations difficult. Refactor the codebase to use dependency injection: Identifies all dependencies that should be injected: DB connections, external API clients, cache clients, config values Converts classes to accept dependencies via constructor injection (preferred) — not property or method injection Defines interfaces for each dependency: services program to the interface, not the concrete implementation Sets up a DI container [InversifyJS / tsyringe / python-dependency-injector / Spring / Dagger] to wire up the dependency graph at startup Shows how to swap the real implementation for a mock in unit tests — no monkey patching required Handles circular dependencies if they exist — refactors to break the cycle Demonstrates the before/after: one class before DI (tightly coupled) and after DI (loosely coupled + testable) Show the interface definitions, the container setup, and a unit test demonstrating mock injection.

Design a blue-green deployment strategy

DevOps
prompt template
Act as a DevOps engineer. I want to implement blue-green deployments for my [application type] to achieve zero-downtime releases and instant rollback capability. Design a blue-green deployment system that: Maintains two identical production environments: blue (currently live) and green (new version) Deploys the new version to the idle environment and runs smoke tests before any traffic shift Shifts traffic from blue to green using [AWS ALB weighted routing / Nginx upstream weights / Kubernetes service selector] Implements a progressive traffic shift: 5% → 25% → 50% → 100% with automated metrics checks at each stage Defines rollback trigger criteria: error rate > [1%], p99 latency > [2s], health check failure → auto-rollback to blue Handles database migrations that are backward compatible with both blue and green simultaneously Automates the full deployment in CI/CD: build → test → deploy green → validate → shift traffic → decommission blue Show the traffic shifting config, the validation step, and the rollback mechanism.

Build a command query bus

Architecture
prompt template
You are a software architect implementing a clean architecture. I want to decouple my controllers from my business logic using a command/query bus pattern. Implement a command query bus that: Defines a Command interface and a Query interface as marker types Implements a CommandBus: dispatches a command to its single registered handler Implements a QueryBus: dispatches a query to its handler and returns the typed result Registers handlers automatically via convention (file naming / decorators / explicit registration) Implements middleware pipeline on the bus: logging, validation, transaction wrapping, authorization — each as a composable middleware Keeps handlers as simple classes with a single handle(command) method — no framework magic inside Shows the full flow: HTTP request → controller extracts command/query → dispatches to bus → handler executes → response returned Show the bus implementations, 2 command handlers, 1 query handler, and the middleware pipeline.

Generate a Kubernetes deployment configuration

DevOps
prompt template
Act as a Kubernetes engineer. I need to deploy my [application type] on Kubernetes in a production-ready way. Application details: Image: [registry/image:tag] Port: [X] CPU/memory requirements: [requests and limits] Environment variables: [list them] Dependencies: [PostgreSQL, Redis, external API] Generate complete Kubernetes manifests including: Deployment with: replica count, rolling update strategy (maxSurge: 1, maxUnavailable: 0), resource requests and limits, liveness and readiness probes Service (ClusterIP for internal, LoadBalancer or Ingress for external traffic) ConfigMap for non-sensitive config, ExternalSecret or Secret for sensitive values HorizontalPodAutoscaler: min [2] replicas, max [10], scale on CPU [70%] and custom metric PodDisruptionBudget: ensure at least [1] replica always available during node maintenance NetworkPolicy: restrict ingress to only allowed sources, restrict egress to only required destinations ServiceAccount with least-privilege RBAC for any cloud API access the app needs Output all manifests in a single YAML file separated by ---.

Implement API mocking for development

Developer Experience
prompt template
You are a developer experience engineer. My frontend team is blocked waiting for the backend API to be built. I need a realistic API mock server that they can develop against immediately. Set up an API mock system that: Generates mock responses from the OpenAPI spec — no manual mock writing Returns realistic data using [Faker.js / factory_boy] seeded from the schema definitions Simulates response latency: configurable per endpoint (default 200ms, P95 500ms) to expose performance issues early Simulates error scenarios on demand: pass a ?simulate_error=429 query param to trigger specific HTTP errors Persists state within a session: a POST creates a resource that can be retrieved via GET — stateful mocking Runs as a standalone server and as a service worker for in-browser mocking (MSW) Auto-updates when the OpenAPI spec changes — no manual mock maintenance Show the mock server setup, the data generation config, and how the frontend switches between mock and real API.

Build a GraphQL data loader

Performance
prompt template
Act as a GraphQL performance engineer. My GraphQL API has N+1 query problems — when resolving a list of [users / products / orders], it fires a separate DB query for each item's related data. Implement DataLoader to batch and cache DB queries: Creates a DataLoader for each many-to-one relationship: [e.g., userLoader, productLoader, categoryLoader] Implements the batch function: receives an array of IDs, runs a single WHERE id IN (...) query, and returns results in the same order as the input IDs Handles missing items correctly: the batch function returns null for IDs not found (not undefined — DataLoader is strict about this) Scopes each DataLoader to the request context — not a singleton (to avoid cross-request caching) Enables caching within the same request: the same ID requested twice in one query is fetched only once Shows the N+1 problem in the before state with query count, and the batched solution in the after state Adds instrumentation: log batch sizes and cache hit rates to validate the optimization Show the DataLoader definitions, their usage in resolvers, and the context setup.

Design a configuration drift detection system

DevOps
prompt template
You are a platform engineer. My production infrastructure and application configuration has drifted from what's defined in version control — I don't know what changed or when. Build a configuration drift detection system that: Defines the desired state in version-controlled config files (Terraform state, Kubernetes manifests, app config) Continuously polls the actual state of [infrastructure / K8s cluster / app config] and compares to desired state Detects drift: reports which resources differ, what the expected value is, and what the actual value is Runs drift checks on a schedule [every 15 minutes] and on every deployment Alerts on drift detected: Slack/PagerDuty notification with the specific diff Distinguishes expected drift (new deployment in progress) from unexpected drift (manual change) Provides a one-command remediation: make drift-fix applies the desired state and restores compliance Show the drift detection script, the comparison logic, and the alerting integration.

Implement a bulk API endpoint

API Design
prompt template
Act as a backend engineer. My clients are making thousands of individual API calls that could be batched. I need to implement a bulk endpoint that lets them send multiple operations in one request. Build a bulk API endpoint that: Accepts an array of operations: { operations: [{ method, path, body }] } following the JSON:API bulk spec or a custom format Processes operations in parallel (where independent) and sequentially (where order-dependent) — detects dependencies automatically Returns a response array with a result per operation: { index, status, body, error } Validates each sub-request independently: one invalid operation does not fail the entire batch Limits batch size to [100] operations per request with a clear error on exceedance Handles partial failure correctly: returns 207 Multi-Status with individual success/failure per operation Implements transactional bulk: optional mode where all operations succeed or all are rolled back Show the batch endpoint, the parallel/sequential processing logic, and example request/response.

Write a post-mortem report

Engineering Practices
prompt template
Act as a senior engineer. We had an incident: [describe the incident: "our payment service was down for 45 minutes on [date] due to a database connection pool exhaustion"]. Write a formal post-mortem report that includes: Incident summary: severity, duration, impact (how many users/transactions affected, estimated revenue impact) Timeline: exact timestamped sequence of events from first alert to full resolution Root cause analysis: the technical root cause AND the systemic/process root cause that allowed it to happen Five Whys analysis: drill down from symptom to root cause What went well: detection, response actions, or systems that worked as intended What went wrong: gaps in monitoring, slow detection, unclear runbooks, missing automation Action items: specific, assigned, time-bound tasks — each with owner, due date, and success metric Write in a blameless, factual tone focused on systems and processes, not individuals.

Implement service mesh configuration

DevOps
prompt template
You are a platform engineer. I want to add a service mesh to my Kubernetes cluster to improve observability, security, and traffic management between microservices. Configure a service mesh ([Istio / Linkerd / Consul Connect]) that: Installs the control plane and injects the sidecar proxy into all application pods Implements mutual TLS (mTLS) between all services: encrypts and authenticates all inter-service traffic Configures traffic policies: circuit breaker (outlier detection), retry policy (3 retries, 500ms timeout per attempt), and load balancing algorithm Sets up canary deployments using traffic weights: route 5% of traffic to the new version via VirtualService Configures observability: automatic distributed traces exported to Jaeger, metrics to Prometheus, access logs to the central log store Implements authorization policies: service A is only allowed to call service B on specific paths and methods Provides a service topology visualization showing all services and their communication patterns Show the Istio VirtualService, DestinationRule, AuthorizationPolicy, and PeerAuthentication YAMLs.

Build a developer feedback collection system

Developer Experience
prompt template
Act as an engineering productivity engineer. I want to collect structured feedback from developers on our internal tools, processes, and developer experience to drive improvements. Build a developer feedback system that: Creates a weekly automated survey: 3-5 questions covering build time satisfaction, deployment confidence, tooling pain points, and an NPS for developer experience Asks follow-up questions based on low scores: if a developer rates build time < 3, ask which step is slowest Aggregates responses over time and calculates weekly trends for each metric Identifies the top 3 pain points by frequency across all responses Publishes a monthly DX report to [Slack / Confluence / Notion] summarizing scores, trends, and top issues Integrates with [GitHub / Jira] to create tickets for top pain points automatically Measures the impact of improvements: shows before/after score comparison when a fix is deployed Show the survey schema, the aggregation logic, and the report generation script.

Implement a tiered storage system

Architecture
prompt template
You are a storage architect. My application generates large amounts of data and storage costs are growing. I need to move data to cheaper storage tiers as it ages. Design a tiered storage system that: Defines storage tiers: hot (DB / fast SSD), warm (object storage S3 / GCS), cold (Glacier / Archive), and the age threshold for each transition Implements a scheduled job that identifies data eligible for tier transition based on age and access frequency Moves data to the next tier without data loss, updates the pointer/location in the metadata DB Implements transparent retrieval: the API fetches from whichever tier holds the data — callers don't know the tier Handles cold tier retrieval latency: triggers async restore from Glacier, returns 202 Accepted, notifies when ready Measures cost per tier and calculates savings from tiering — includes a cost projection dashboard Implements data lifecycle policies: auto-delete records after [7 years] per data retention policy Show the tiering job, the retrieval abstraction, and the cost calculation logic.

Build a cross-service event schema registry

Architecture
prompt template
Act as a platform engineer. My microservices are producing and consuming events, but there's no shared schema registry — producers and consumers drift out of sync, causing runtime failures. Build a schema registry system that: Defines all events as versioned schemas in a central repository (Avro / Protobuf / JSON Schema) Implements schema evolution rules: backward compatible (new optional fields only), forward compatible, or full compatibility — enforces via CI check Registers schemas with [Confluent Schema Registry / AWS Glue / custom] and assigns a schema ID Producers serialize events with the schema ID embedded — no schema sent on every message Consumers fetch schema by ID from the registry at startup and cache it locally Validates every produced event against its registered schema before publishing — fails fast on mismatch Generates type-safe code (TypeScript types, Python dataclasses, Java POJOs) from schemas for all consuming services Show the schema definition, the producer with validation, the consumer with schema resolution, and the CI compatibility check.

Implement graceful shutdown

Reliability
prompt template
You are a backend engineer. My application receives SIGTERM when the container/pod is being terminated and currently drops in-flight requests, aborts open DB connections, and leaves jobs in an inconsistent state. Implement graceful shutdown that: Listens for SIGTERM and SIGINT signals and starts the shutdown sequence Stops accepting new connections immediately (close the HTTP server listener) Waits for all in-flight requests to complete with a maximum wait of [30 seconds] — forcibly terminates after timeout Stops the job queue worker: finishes the current job, stops pulling new ones Closes database connection pool: waits for all active queries to complete Closes cache connections, message queue connections, and any open file handles Logs a shutdown summary: how many requests were in-flight, how long shutdown took, exit code Show the shutdown sequence, the timeout logic, and a test that verifies no requests are dropped during a shutdown.

Design a cost optimization strategy

DevOps
prompt template
Act as a FinOps engineer. My cloud infrastructure bill for [AWS / GCP / Azure] is [X$/month] and growing. I need to identify and implement cost optimizations. Deliver a cloud cost optimization plan that: Audits the bill by service: identify the top 5 cost drivers and their % of total spend Identifies waste: idle EC2/GCE instances, unattached EBS volumes, unused IPs, oversized RDS instances, stale snapshots Implements rightsizing: recommends correct instance sizes based on actual CPU/memory utilization over the last 30 days Designs a Reserved Instance / Committed Use strategy for stable baseline workloads — calculate payback period and savings Implements autoscaling to eliminate over-provisioning for variable workloads Configures S3/GCS lifecycle policies to move old data to cheaper tiers automatically Sets up budget alerts: alert at 80% of monthly budget, and a hard ceiling alert at 100% Quantify the expected monthly savings for each optimization with a prioritized implementation order.

Build a feature usage analytics system

Engineering Practices
prompt template
You are a product engineer. I want to track which features users are actually using in my application so I can make data-driven decisions about what to build, improve, or deprecate. Build a feature usage analytics system that: Defines a simple event tracking API: track(userId, eventName, properties) — called from feature code Implements the event schema: consistent naming convention (Object Verb: "Document Exported", "Filter Applied") Batches events and sends them asynchronously — never blocks the user action Stores events in an analytics-optimized store: [Segment / Mixpanel / Amplitude / ClickHouse / BigQuery] Builds a feature adoption dashboard: unique users per feature, DAU/MAU ratio, feature retention (used in week 2+) Implements funnel analysis: tracks drop-off rates through a multi-step flow Sets up feature deprecation alerts: notify the team if a feature's usage drops below [X users/month] — candidate for removal Show the tracking call, the event schema, the batch sender, and the dashboard query.

Implement cross-origin resource sharing (CORS)

Security
prompt template
Act as a security engineer. I need to configure CORS correctly on my [REST API / GraphQL API] so that legitimate web clients can make requests while blocking unauthorized cross-origin access. Implement a secure CORS configuration that: Defines the exact list of allowed origins — never uses * wildcard in a credentialed request Configures allowed methods (GET, POST, PUT, DELETE, OPTIONS) and allowed headers per route Handles the preflight OPTIONS request correctly: responds with the correct CORS headers and 204 status Sets Access-Control-Allow-Credentials: true only on routes that require cookies or auth headers Sets a max-age for preflight caching to reduce OPTIONS requests in production (1 hour) Implements origin validation dynamically: read the Origin header and compare to an allowlist — supports multiple environments Handles CORS errors clearly: returns a meaningful error when an origin is rejected, for easier debugging Show the CORS middleware, the allowed origins config, and how to test CORS behavior with curl.

Build a dead letter queue handler

Reliability
prompt template
You are a messaging systems engineer. My message queue has a dead letter queue (DLQ) with messages that failed processing. These messages need to be investigated, potentially fixed, and reprocessed. Build a DLQ management system that: Reads messages from the DLQ: [SQS DLQ / RabbitMQ dead letter exchange / Kafka dead letter topic] Enriches each DLQ message with context: original queue, failure reason, retry count, first/last failure timestamp Categorizes failures: transient (network timeout, downstream 503), permanent (invalid payload, business rule violation), and unknown Implements a retry strategy per category: auto-retry transient failures, alert on permanent failures for manual review Provides an admin API to: list DLQ messages, view message detail, manually retry a single message, batch retry by category Sends daily DLQ digest: count by category, oldest message age, trend vs. yesterday Auto-purges DLQ messages older than [30 days] after archiving to cold storage Show the DLQ reader, the categorization logic, the retry handler, and the admin API.

Implement a custom ORM layer

Architecture
prompt template
Act as a backend engineer. I want to build a lightweight ORM layer for my [language] application using a bare database driver [pg / mysql2 / sqlite3 / database/sql] to avoid the overhead and magic of a full ORM. Build a thin query builder that: Provides a fluent interface: db.table('users').select('id, email').where({ active: true }).limit(10) Generates parameterized SQL for all operations — never string-interpolates user input Supports: SELECT with WHERE, ORDER BY, LIMIT, OFFSET; INSERT with returning; UPDATE with WHERE; DELETE with WHERE Maps result rows to typed model objects using a configurable mapper function per table Supports JOIN operations: INNER JOIN, LEFT JOIN with alias support Handles transactions: db.transaction(async (tx) => { ... }) with automatic rollback on exception Logs all generated SQL and parameters in development mode (disabled in production) Show the query builder implementation, 5 usage examples, and a comparison to raw SQL it replaces.

Build a zero-downtime database migration tool

Database
prompt template
You are a database engineer. I need to perform large-scale schema changes on a live PostgreSQL database with millions of rows and strict zero-downtime requirements. Build a zero-downtime migration tool that: Analyzes the requested schema change and determines the minimum safe steps using expand-contract Creates new columns/tables as nullable and without constraints first Backfills data in batches of [5000 rows] with a configurable delay between batches to limit lock contention Uses CREATE INDEX CONCURRENTLY for all new indexes — never blocks reads/writes Adds constraints using NOT VALID first, then VALIDATE CONSTRAINT in a separate transaction Switches the application over to the new schema while the old is still intact (dual-write period if needed) Drops old columns/tables only after verifying no traffic is using them — provides a read-traffic analysis step Show the migration planner, the batch backfill with progress tracking, and the validation step.

Implement a content moderation system

Feature Development
prompt template
Act as a backend engineer. My platform has user-generated content [posts / comments / images / video] that needs to be moderated for [spam / harassment / NSFW content / illegal content]. Build a content moderation system that: Implements pre-moderation for high-risk content and post-moderation for standard content — defines the criteria Integrates with [AWS Rekognition / Google Vision / OpenAI Moderation / Azure Content Safety] for automated classification Defines confidence thresholds: auto-approve (high confidence clean), auto-reject (high confidence violation), route to human review (uncertain) Implements an appeal flow: users can appeal auto-rejections, routed to senior moderator Builds the moderation queue UI: shows content, AI confidence scores, similar past decisions, and action buttons Tracks moderator decisions to retrain the model: collect labeled data from human moderations Measures moderation metrics: false positive rate, false negative rate, average review time per item Show the moderation pipeline, the threshold config, and the appeal endpoint.

Design a multi-region active-active architecture

Architecture
prompt template
You are a distributed systems architect. I need my application to be available in [2 / 3] regions simultaneously with active-active configuration to minimize latency for global users and eliminate single-region as a failure point. Design a multi-region active-active architecture that: Routes users to the nearest region using [latency-based DNS routing / GeoDNS / Anycast] Handles data consistency: classifies data into [user-local data / global shared data] and applies the right replication strategy per type Implements cross-region database replication: [CockroachDB / DynamoDB Global Tables / Spanner / PostgreSQL BDR] with conflict resolution policy Handles write conflicts: last-write-wins, CRDT, or application-level conflict resolution — recommend for my data types Implements health-based failover: if a region's error rate exceeds [5%], traffic shifts to healthy regions automatically Manages session state: users are re-routed without losing their session if their region fails Calculates the cost vs. resilience tradeoff: what does active-active cost vs. active-passive for my scale? Show the traffic routing config, the data replication setup, and the failover trigger logic.

Build a dynamic form builder backend

Feature Development
prompt template
Act as a full-stack engineer. I need to build a dynamic form builder where admins define form schemas and end users fill them out — like Typeform or Google Forms, but embedded in my platform. Build a form builder backend that: Defines the form schema model: form metadata (title, description, submit button label) + ordered list of fields (type, label, placeholder, validation rules, conditional visibility logic) Supports field types: text, textarea, email, phone, number, date, select, multiselect, checkbox, radio, file upload, section divider Implements conditional logic: show/hide field B if field A value equals X Validates form submissions against the schema: required fields, type validation, regex patterns, min/max Stores submissions with: form version reference, submitter ID (or anonymous), timestamp, and field-value pairs Generates a submission report: CSV export, summary statistics per field (response rate, most common answer) Supports form versioning: existing submissions are linked to the schema version they were submitted against Show the form schema model, the submission validation logic, and the report generation query.

Implement a serverless function architecture

Architecture
prompt template
You are a cloud architect. I want to migrate [describe the workload: image processing pipeline / webhook handlers / scheduled reports / API endpoints] to serverless functions. Design a serverless architecture using [AWS Lambda / GCP Cloud Functions / Azure Functions / Vercel Functions] that: Identifies which workloads are a good fit for serverless (event-driven, variable load, short duration) and which are not Designs the function decomposition: one function per responsibility — not a monolithic Lambda Handles cold starts: identify latency-sensitive functions and apply provisioned concurrency or keep-warm strategies Manages shared state: functions are stateless — shows where to use [DynamoDB / Redis / S3] for state Configures function-to-function communication: direct invocation vs. event bus (EventBridge / Pub/Sub) Sets memory, timeout, and concurrency limits per function based on expected workload Implements observability: structured logging, distributed tracing with cold start detection, cost per invocation tracking Show the function definitions, the IaC config, and the event source mappings.

Generate a performance budget

Performance
prompt template
Act as a performance engineer. My web application's performance has degraded over time — each feature addition made it slightly slower and now users notice. I need to establish and enforce performance budgets. Create a performance budget system that: Measures the current performance baseline: Core Web Vitals (LCP, CLS, INP), Time to Interactive, Total Blocking Time, bundle size per route Defines budget thresholds per metric: [LCP < 2.5s, CLS < 0.1, bundle size < 200KB gzipped per route] Integrates budget checks into CI: builds fail if any budget is exceeded (using [bundlesize / Lighthouse CI / web-vitals-ci]) Generates a performance report on every merge to main: shows current values vs. budget, trend over last 30 days Identifies the biggest current violations and provides specific remediation steps for each Implements real-user monitoring (RUM): collects Web Vitals from real users in production, not just synthetic tests Creates a performance regression playbook: what to do when a budget is exceeded — who reviews, how to fix or justify an exception Show the Lighthouse CI config, the CI budget check step, and the bundle analyzer setup.

Build a SaaS billing system integration

Feature Development
prompt template
You are a backend engineer. I need to integrate a subscription billing system using [Stripe Billing / Chargebee / Recurly] with my SaaS application. Build a complete billing integration that: Implements subscription lifecycle: create customer, subscribe to plan, upgrade, downgrade, cancel — all via API Handles billing webhooks: invoice.paid, invoice.payment_failed, customer.subscription.updated, customer.subscription.deleted Implements a metered billing feature: tracks [API calls / seats / storage used] and reports usage to the billing provider monthly Handles failed payments: retry logic on the provider side + dunning emails + service suspension after [X days] unpaid Implements a trial period: [14-day] trial, reminder emails at day 7 and day 13, automatic subscription start on day 15 Provides a customer billing portal URL: lets customers manage their subscription, payment method, and download invoices Implements proration: calculates the correct amount when a customer upgrades mid-billing-cycle Show the subscription creation flow, the webhook handler, the usage reporting job, and the dunning state machine.

Implement a message queue consumer group

Backend Development
prompt template
Act as a messaging systems engineer. I need to build a consumer group for [Kafka / RabbitMQ / SQS] that processes [describe the message type, e.g., order events] at scale with multiple parallel workers. Build a consumer group implementation that: Configures partition/shard assignment across [N] worker instances for parallel processing Implements manual offset/ack commit only after successful processing — never auto-commit before processing completes Handles rebalancing gracefully: pauses processing, commits current offsets, resumes after rebalance completes Processes messages in batches of [100] for throughput, with per-message error isolation within the batch Implements backpressure: slows consumption if downstream processing (DB writes, API calls) can't keep up Sends unprocessable messages to a dead letter queue after [3] failed attempts Exposes consumer lag metrics per partition for monitoring Use [kafka-node / kafkajs / aio-pika / aws-sdk]. Show the consumer setup, the batch processing loop, and the offset commit logic.

Design a read replica routing strategy

Database
prompt template
You are a database engineer. My application has a primary database with [N] read replicas, but all queries currently hit the primary, causing unnecessary load. Implement a read/write splitting strategy that: Routes all writes (INSERT, UPDATE, DELETE) to the primary database automatically Routes reads to replicas by default, with an explicit override for reads that require strong consistency Handles replication lag: after a write, subsequent reads from the same request use the primary for [X seconds] to avoid stale reads Implements replica health checks: removes a lagging or unhealthy replica from the pool automatically Load balances reads across healthy replicas using [round-robin / least-connections] Wraps the routing logic transparently in the DAL so application code doesn't need to specify primary vs. replica per query Monitors and alerts on replication lag exceeding [X seconds] Show the connection routing logic, the consistency override mechanism, and the health check implementation.

Build a request validation and sanitization layer

Security
prompt template
Act as a security-focused backend engineer. I need a centralized request validation and sanitization layer to prevent injection attacks and malformed data from reaching my business logic. Build a validation and sanitization system that: Validates all incoming requests against a schema before any controller logic executes Sanitizes string inputs: strips or escapes HTML to prevent XSS, trims whitespace, enforces max length Rejects requests with unexpected extra fields (strict schema mode) to prevent mass assignment vulnerabilities Validates and sanitizes file uploads: checks magic bytes (not just extension), strips EXIF metadata from images Escapes or parameterizes any values used in SQL, shell commands, or regex construction Returns validation errors before any DB or external calls are made — fails fast Logs rejected requests with the reason, for abuse pattern detection Show the validation middleware, the sanitization utilities, and an example applied to a user-input-heavy endpoint.

Implement a saga pattern for distributed transactions

Architecture
prompt template
You are a distributed systems architect. I have a business process [e.g., "place order → reserve inventory → charge payment → schedule shipping"] that spans multiple microservices and needs transactional consistency without a distributed transaction. Implement the saga pattern that: Evaluates choreography-based vs. orchestration-based saga for my use case — recommend and justify Defines each step as a local transaction with a corresponding compensating action (undo) Implements the saga orchestrator (if chosen): tracks saga state, invokes each step in sequence, triggers compensation on failure Handles partial failure: if step 3 fails, executes compensating actions for steps 2 and 1 in reverse order Persists saga state to survive orchestrator restarts — resumes in-flight sagas on startup Implements idempotent step handlers so retries don't cause duplicate side effects Provides observability: a saga execution log showing each step's status and timing Show the saga definition, the orchestrator, one step with its compensating action, and the failure/compensation flow.

Write a database connection pooling configuration

Performance
prompt template
Act as a backend performance engineer. My application is experiencing connection exhaustion errors under load: [error message, e.g., "too many connections" / "pool timeout"]. Diagnose and configure database connection pooling that: Calculates the correct pool size using the formula: connections = ((core_count * 2) + effective_spindle_count) — adjusted for my workload type Sets min and max pool size appropriately: avoids both connection starvation and over-provisioning Configures connection timeout, idle timeout, and max lifetime to recycle stale connections Implements connection validation (test-on-borrow) to avoid handing out dead connections Ensures connections are always released in a finally block — audits the codebase for leaked connections Separates pools for read vs. write workloads if using read replicas Adds pool metrics: active connections, idle connections, wait time, wait queue length Show the pool configuration for [PgBouncer / HikariCP / pg-pool / SQLAlchemy pool], and the calculation behind the chosen values.

Build a client-side state management architecture

Frontend Development
prompt template
You are a frontend architect. My [React / Vue / Angular] application's state management has become unpredictable — state is scattered, hard to debug, and causes unnecessary re-renders. Design a state management architecture that: Separates state into categories: server state (API data), client state (UI state), and URL state — recommends the right tool per category Implements server state using [React Query / SWR / Apollo Client] with caching, background refetching, and optimistic updates Implements client state using [Zustand / Redux Toolkit / Pinia / Signals] with a normalized shape (no deeply nested objects) Defines clear boundaries: components read state via selectors, never mutate state directly Prevents unnecessary re-renders: memoization strategy and selector-based subscriptions Handles derived state with computed selectors rather than storing duplicated data Documents the state architecture with a diagram showing where each type of state lives and how it flows Show the store setup, one server-state hook, one client-state slice, and a component consuming both correctly.

Implement API request signing

Security
prompt template
Act as a security engineer. I need to secure server-to-server API calls [e.g., webhooks, internal service calls, partner integrations] using request signing instead of static API keys alone. Implement HMAC-based request signing that: Generates a signature from: HTTP method, path, timestamp, and request body hash, signed with a shared secret using HMAC-SHA256 Includes the signature, timestamp, and key ID in request headers Validates on the receiving end: recomputes the signature and compares using constant-time comparison (prevents timing attacks) Rejects requests with a timestamp older than [5 minutes] to prevent replay attacks Supports key rotation: multiple valid keys can verify signatures simultaneously during rotation window Provides a client-side signing helper/SDK so integrators don't need to implement HMAC manually Logs and alerts on repeated signature validation failures (possible attack or misconfigured client) Show the signing function, the verification middleware, and example signed request/response.

Design a multi-step checkout flow backend

Feature Development
prompt template
You are a backend engineer for an e-commerce platform. I need to implement the backend for a multi-step checkout flow: cart review → shipping → payment → confirmation. Build a checkout backend that: Persists checkout state across steps using a checkout session (server-side, not just client state) with a TTL of [30 minutes] Validates cart contents at each step: stock availability, price changes since cart was created, promo code validity Calculates totals server-side at every step: subtotal, tax (based on shipping address), shipping cost, discounts — never trusts client-sent totals Reserves inventory temporarily when checkout starts, releases it if checkout is abandoned or fails Handles the payment step atomically with order creation: order is only created after payment confirmation, using idempotency keys Sends order confirmation via email/SMS and triggers downstream fulfillment events only after payment succeeds Handles abandoned checkout recovery: scheduled job identifies abandoned sessions and triggers a reminder Show the checkout session model, the step validation logic, and the atomic order-creation-on-payment flow.

Build a code coverage enforcement pipeline

Testing
prompt template
Act as a QA engineering lead. I want to enforce meaningful code coverage standards in CI without encouraging low-value tests written just to hit a number. Set up a coverage enforcement system that: Configures coverage collection using [Istanbul/nyc / coverage.py / JaCoCo] with branch coverage enabled (not just line coverage) Sets differentiated thresholds: [80%] for new/changed code in a PR, [60%] minimum for the overall codebase Fails the PR check only on newly added code falling below threshold — doesn't block on pre-existing legacy code Excludes appropriately: generated code, config files, type definitions, and trivial getters/setters from coverage requirements Posts a coverage diff comment on the PR showing exactly which new lines are uncovered Tracks coverage trend over time and flags a declining trend even if the absolute number is still above threshold Documents guidance on what NOT to test just for coverage (e.g., simple pass-through functions) to avoid gaming the metric Show the CI coverage step, the threshold configuration, and the PR comment bot setup.

Implement an outbox pattern for reliable event publishing

Architecture
prompt template
You are a distributed systems engineer. My service writes to its database and publishes an event to a message broker, but if the process crashes between the DB write and the publish, the event is lost — causing data inconsistency across services. Implement the transactional outbox pattern that: Writes the business data change and the event payload to an outbox table in the same database transaction Implements a relay process that polls the outbox table for unpublished events and publishes them to [Kafka / RabbitMQ / SNS] Marks events as published only after broker acknowledgment — retries on failure Uses change data capture (CDC) via [Debezium] as an alternative to polling, if lower latency is required — explains the tradeoff Ensures exactly-once-effective delivery on the consumer side using idempotent consumers (since outbox gives at-least-once) Cleans up published events from the outbox table after [X days] via a scheduled job Monitors outbox table growth and publish lag as key health metrics Show the outbox table schema, the transactional write, the relay/publisher process, and the cleanup job.

Write a code complexity analysis report

Code Quality
prompt template
Act as a code quality engineer. I want to analyze my codebase for complexity hotspots that are likely sources of bugs and slow development. Analyze the codebase and generate a report that: Calculates cyclomatic complexity per function/method using [ESLint complexity rule / radon / SonarQube] and flags anything above [10] Identifies the largest files and functions by line count — flags files over [500 lines] and functions over [50 lines] Detects code duplication: finds near-duplicate code blocks that should be extracted into shared functions Measures coupling: identifies modules with the highest number of incoming/outgoing dependencies (potential god objects) Cross-references complexity with git history: which complex files change most frequently (highest risk for bugs) Prioritizes a refactoring backlog: ranks the top 10 files by (complexity × change frequency) as the highest-value refactor targets Sets ongoing complexity budgets in CI to prevent new hotspots from being introduced Show the analysis commands/tooling, and the format of the prioritized findings report.

Build a request context propagation system

Architecture
prompt template
Act as a backend engineer. I need to propagate request-scoped context (request ID, user ID, tenant ID, trace ID) through my application without passing it as a parameter to every single function. Implement request context propagation that: Uses [AsyncLocalStorage (Node.js) / contextvars (Python) / ThreadLocal (Java) / context.Context (Go)] to store request-scoped values Sets the context at the entry point (middleware) for every incoming request: request ID, auth user, tenant, trace ID Makes context accessible anywhere in the call stack without threading it through function signatures Propagates context correctly across async boundaries: promises, callbacks, and async/await chains Automatically injects context values into every log statement (structured logging) without manual passing Propagates trace context to outgoing HTTP calls and message queue publishes (for distributed tracing) Correctly isolates context between concurrent requests — verifies no context leakage under load testing Show the context setup middleware, an example of reading context deep in the call stack, and the log injection.

Design an API deprecation and sunset process

API Design
prompt template
You are an API product engineer. I need to formally deprecate and eventually remove an old API endpoint / version while minimizing disruption to existing clients. Design a deprecation process that: Announces deprecation with a minimum [6-month] notice period before removal Adds a Deprecation and Sunset HTTP header (per RFC 8594) to all responses from the deprecated endpoint Logs every call to the deprecated endpoint with the caller's API key/client ID to build a list of who needs migration outreach Sends direct notifications (email + dashboard banner) to identified active users of the deprecated endpoint Provides a clear migration guide: old request/response vs. new, with a mapping table for any renamed or restructured fields Implements a usage decline dashboard to track migration progress and identify stragglers close to the sunset date On sunset date, returns HTTP 410 Gone with a message pointing to the migration guide — never silently breaks Show the deprecation header middleware, the usage logging, and the sunset response format.

Implement a rollback-safe blue/green database schema strategy

Database
prompt template
Act as a database engineer. I need to make a schema change that's safe to roll back even after the application code deploys, in case the deployment needs to be reverted. Design a rollback-safe schema migration that: Adds new columns/tables without removing or renaming old ones — old and new schema coexist temporarily Ensures the previous application version continues to function correctly against the new schema (backward compatibility check) Uses dual writes during the transition: application writes to both old and new columns until cutover is confirmed stable Provides a verified rollback script that reverts the application deploy without requiring a reverse schema migration Defines a "safe to clean up" checklist: confirms no traffic depends on the old schema before removing it Runs the cleanup migration (dropping old columns/tables) as a separate, later deployment — never bundled with the risky change Documents the full timeline: deploy new schema → deploy new code (dual writes) → verify → deploy code cutover → cleanup migration (days later) Show the migration steps in order, the dual-write code, and the rollback procedure at each stage.

Discover More Prompts

Supercharge your operational systems with templates optimized across alternative verticals.