Best Practices

Proven patterns for writing effective AI coding rules and maintaining standards across repos.

AI Rules for i18n and Localization

AI hardcodes English strings in components and templates. Rules for message catalogs, ICU message format, date/number Intl formatting, pluralization, and RTL layout support.

7 min read·Jan 27, 2026

AI Rules for Feature Flags

AI hardcodes feature toggles as if-statements scattered through the codebase. Rules for flag services, typed flags, gradual rollout, kill switches, and stale flag cleanup.

7 min read·Oct 14, 2025

AI Rules for Database Migrations

AI generates migrations that lock tables for minutes and drop data. Rules for zero-downtime patterns, two-phase column changes, data backfills, rollback, and migration testing.

8 min read·Aug 25, 2025

AI Rules for Background Jobs and Queues

AI processes everything in the request handler — blocking users for seconds. Rules for job queues (BullMQ, Celery), retry with backoff, dead letter queues, idempotent jobs, and worker scaling.

8 min read·Jul 8, 2025

AI Rules for Regex Patterns

AI generates regex that's either vulnerable to ReDoS or fails on edge cases. Rules for safe patterns, named groups, readability, and using parser libraries instead.

7 min read·Jul 3, 2025

AI Rules for Protobuf and gRPC

AI-generated proto files break backward compatibility and use wrong field types. Rules for schema evolution, field numbering, service design, and gRPC error handling.

7 min read·Jun 4, 2025

AI Rules for Webhook Handling

AI processes webhooks synchronously with no signature check. Rules for HMAC signature verification, idempotent processing, async queuing, retry handling, and event logging.

7 min read·May 26, 2025

AI Rules for Screen Reader Compatibility

AI builds visual-only UIs invisible to screen readers. Rules for landmark regions (nav, main, aside), heading hierarchy (h1-h6 no skips), accessible names for all controls, logical reading order, dynamic content announcements, and testing with NVDA and VoiceOver.

8 min read·Apr 8, 2025

AI Rules for Keyboard Navigation

AI builds mouse-only interfaces. Rules for logical tab order, focus management in modals and SPAs, roving tabindex for composite widgets, skip-to-content links, keyboard shortcut design, and :focus-visible styling that does not annoy mouse users.

7 min read·Apr 7, 2025

AI Rules for ARIA Attributes

AI misuses or ignores ARIA. Rules for the five rules of ARIA usage, correct role assignments, aria-expanded and aria-selected state attributes, aria-live regions for dynamic updates, and the most common ARIA anti-patterns to avoid.

7 min read·Apr 6, 2025

AI Rules for WCAG Accessibility

AI fails WCAG on every criterion. Rules for perceivable content (alt text, contrast, captions), operable controls (keyboard, timing, seizures), understandable interfaces (labels, errors, predictability), robust markup (valid HTML, ARIA), and axe-core accessibility testing in CI.

8 min read·Apr 5, 2025

AI Rules for Progressive Enhancement

AI builds JS-dependent apps that show blank pages. Rules for HTML-first server rendering, form actions that work without JavaScript, CSS-only interactive patterns, feature detection with fallbacks, and graceful degradation that preserves core functionality.

7 min read·Apr 4, 2025

AI Rules for Offline-First Apps

AI treats offline as an error. Rules for local-first data architecture, IndexedDB as primary store, sync engines for background reconciliation, conflict resolution strategies, optimistic UI patterns, and connectivity-aware UX indicators.

8 min read·Apr 3, 2025

AI Rules for Service Workers and PWA

AI registers service workers with no caching strategy. Rules for cache-first and network-first strategies, Workbox precaching, runtime route caching, service worker update prompts, PWA installability criteria, and offline fallback pages.

8 min read·Apr 2, 2025

AI Rules for Web Workers

AI blocks the main thread with heavy computation. Rules for Web Worker offloading, structured clone data transfer, Comlink for RPC-style messaging, SharedWorker for cross-tab state, worker pool patterns, and Transferable objects for zero-copy.

7 min read·Apr 1, 2025

AI Rules for Server-Sent Events

AI uses WebSocket for one-way push. Rules for native EventSource API, SSE vs WebSocket selection criteria, streaming response patterns, built-in automatic reconnection, typed event channels, Last-Event-ID resume, and serverless-compatible SSE.

7 min read·Mar 31, 2025

AI Rules for GraphQL Subscriptions

AI polls GraphQL queries every second. Rules for WebSocket-based subscriptions, subscription resolvers with async iterators, Redis pub/sub backend, event filtering per subscriber, connection lifecycle management, and horizontal scaling strategies.

7 min read·Mar 30, 2025

AI Rules for Pub/Sub Patterns

AI couples services with direct calls. Rules for topic-based event broadcasting, fan-out to multiple subscribers, message attribute filtering, at-least-once delivery semantics, subscription lifecycle management, and when to use pub/sub vs point-to-point queues.

7 min read·Mar 29, 2025

AI Rules for Message Queues

AI processes everything inline. Rules for queue selection (SQS, BullMQ, RabbitMQ), producer/consumer decoupling, dead letter queues, FIFO ordering guarantees, at-least-once with idempotent consumers, and backpressure with concurrency limits.

8 min read·Mar 28, 2025

AI Rules for Distributed Transactions

AI wraps cross-service calls in one transaction. Rules for saga choreography and orchestration, compensating actions for rollback, transactional outbox pattern, two-phase commit trade-offs, and eventual consistency with conflict resolution.

8 min read·Mar 27, 2025

AI Rules for Idempotency

AI creates duplicates on retries and double-charges on timeouts. Rules for Idempotency-Key headers, Redis/database deduplication stores, naturally idempotent operations, conditional updates with ETags, and idempotency key TTL lifecycle.

7 min read·Mar 26, 2025

AI Rules for Retry Patterns

AI retries immediately and infinitely. Rules for exponential backoff with jitter, max retry limits, idempotent-only retries, error classification (retryable vs permanent), retry budgets, and AbortController timeout integration.

7 min read·Mar 25, 2025

AI Rules for Circuit Breaker Patterns

AI retries infinitely with no backoff. Rules for circuit breaker state machines (closed/open/half-open), failure thresholds, graceful fallback responses, health probe half-open testing, bulkhead isolation, and opossum library patterns.

7 min read·Mar 24, 2025

AI Rules for Service Mesh Patterns

AI has no mTLS or traffic management between services. Rules for sidecar proxy architecture, mutual TLS for zero-trust, traffic splitting for canary deployments, integrated observability, retry/timeout policies, and when a service mesh is worth the complexity.

8 min read·Mar 23, 2025

AI Rules for API Gateway Patterns

AI exposes microservices directly to clients. Rules for API gateway request routing, edge rate limiting, authentication offloading, response aggregation from multiple services, request/response transformation, and gateway selection criteria.

8 min read·Mar 22, 2025

AI Rules for SSO Implementation

AI builds custom SSO instead of supporting standards. Rules for SAML 2.0 service provider integration, OIDC support, just-in-time user provisioning, federated session management, domain-based SSO enforcement, and enterprise IdP requirements.

8 min read·Mar 21, 2025

AI Rules for Two-Factor Authentication

AI sends SMS codes with no rate limits or recovery. Rules for TOTP with authenticator apps, WebAuthn passkeys, hashed recovery codes, enrollment UX with QR codes, graceful enforcement policies, and backup method management.

8 min read·Mar 20, 2025

AI Rules for Social Authentication

AI stores provider tokens in localStorage with no linking. Rules for NextAuth provider configuration, safe account linking with verification, profile data sync, token refresh for API access, multi-provider management, and login button UX.

7 min read·Mar 19, 2025

AI Rules for Push Notifications

AI requests push on page load and blasts everyone. Rules for progressive push permission UX, service worker registration, rich notification payloads with actions, audience segmentation, frequency capping, and opt-out management.

7 min read·Mar 18, 2025

AI Rules for Maps Integration

AI loads the full Maps SDK on every page. Rules for lazy loading map libraries, marker clustering for large datasets, custom map styles, static image fallbacks for non-interactive contexts, and map API cost optimization.

7 min read·Mar 17, 2025

AI Rules for Geolocation Features

AI requests location on page load with no context. Rules for progressive permission UX, IP geolocation fallback, PostGIS spatial queries for nearby search, privacy-preserving fuzzy location, reverse geocoding, and timezone detection.

7 min read·Mar 16, 2025

AI Rules for Realtime Collaboration

AI uses last-write-wins for concurrent edits. Rules for CRDTs and operational transforms, presence awareness with cursors, conflict-free merging, optimistic local-first updates, undo/redo in collaborative contexts, and awareness indicators.

8 min read·Mar 15, 2025

AI Rules for Chat and Messaging

AI polls every second for new messages. Rules for WebSocket real-time delivery, message ordering with sequence numbers, read receipts, typing indicators, offline queuing with sync, and conversation threading models.

8 min read·Mar 14, 2025

AI Rules for Video Streaming

AI serves video as a full file download. Rules for HLS adaptive bitrate streaming, CDN edge delivery, FFmpeg transcoding pipelines, thumbnail sprite generation, HTTP range request support, and video player integration.

8 min read·Mar 13, 2025

AI Rules for Image Processing

AI processes images inline with no size limits. Rules for sharp-based resize/convert pipelines, async background processing, WebP/AVIF output, thumbnail generation at multiple sizes, EXIF metadata stripping, and upload validation.

7 min read·Mar 12, 2025

AI Rules for CSV Processing

AI splits on commas and breaks on quoted fields. Rules for Papa Parse/csv-parse streaming, encoding detection, header mapping with column aliases, per-row Zod validation, edge case handling, and memory-efficient large file processing.

7 min read·Mar 11, 2025

AI Rules for PDF Generation

AI concatenates HTML strings for PDFs with no page breaks. Rules for Puppeteer/Playwright headless rendering, React-to-PDF pipelines, Handlebars templates, CSS page break control, header/footer injection, and async generation.

7 min read·Mar 10, 2025

AI Rules for Data Export and Import

AI exports synchronously and times out. Rules for async background export jobs, streaming CSV/JSON generation, chunked import with row-level validation, progress tracking with webhooks, and GDPR data portability compliance.

7 min read·Mar 9, 2025

AI Rules for Audit Logging

AI uses console.log or logs nothing. Rules for structured audit events with who/what/when/why, immutable append-only trails, compliance-ready retention policies, tamper-evident logging, and queryable audit search.

8 min read·Mar 8, 2025

AI Rules for Multi-Tenancy

AI builds single-tenant apps. Rules for tenant isolation with row-level security, schema-per-tenant vs shared-database trade-offs, tenant-aware middleware, data isolation guarantees, and cross-tenant query prevention.

8 min read·Mar 7, 2025

AI Rules for Subscription Billing

AI builds subscriptions with no proration or dunning. Rules for plan management with Stripe Billing, trial-to-paid conversion, proration on plan changes, dunning for failed renewals, usage-based metered billing, and revenue recognition.

8 min read·Mar 6, 2025

AI Rules for Checkout Flows

AI builds leaky multi-page checkout. Rules for single-page checkout design, cart persistence across sessions, address validation and autocomplete, live order summary, graceful error recovery, and conversion rate optimization.

7 min read·Mar 5, 2025

AI Rules for Payment Integration

AI processes raw card numbers server-side with no webhook verification. Rules for Stripe Checkout sessions, webhook signature verification, idempotent charges, refund workflows, subscription lifecycle, and PCI DSS compliance.

8 min read·Mar 4, 2025

AI Rules for Notification Systems

AI sends notifications inline with no preferences or batching. Rules for multi-channel delivery (email, push, in-app), user preference management, intelligent batching, template systems, and delivery tracking with retry.

8 min read·Mar 3, 2025

AI Rules for Search Implementation

AI searches with LIKE '%query%'. Rules for Postgres full-text search, Elasticsearch integration, BM25 relevance scoring, fuzzy matching with typo tolerance, faceted filtering, and debounced search-as-you-type.

8 min read·Mar 2, 2025

AI Rules for Data Modeling

AI maps classes to tables 1:1 with no relationship analysis. Rules for entity-relationship modeling, cardinality constraints, polymorphic data patterns, soft delete strategies, temporal data versioning, and schema evolution.

8 min read·Mar 1, 2025

AI Rules for NoSQL Patterns

AI uses NoSQL like a relational DB. Rules for access-pattern-driven data modeling, single-table design in DynamoDB, strategic denormalization, consistency model selection, and clear criteria for choosing NoSQL vs SQL.

8 min read·Feb 28, 2025

AI Rules for File Upload Handling

AI stores uploads on the local filesystem and trusts filenames. Rules for S3/R2 object storage, MIME validation, signed URLs for private files, size limits, and virus scanning.

7 min read·Feb 28, 2025

AI Rules for Database Design

AI builds tables with no indexes or constraints. Rules for normalization to 3NF, strategic index design, foreign key constraints, migration-first workflows, query performance analysis, and schema evolution strategies.

8 min read·Feb 27, 2025

AI Rules for CSS and Styling

AI-generated CSS is riddled with specificity issues, magic numbers, and non-responsive layouts. Rules for your styling approach — Tailwind, CSS Modules, or vanilla CSS.

7 min read·Feb 26, 2025

AI Rules for Microservice Patterns

AI builds distributed monoliths. Rules for service boundary design, API contract testing, circuit breaker resilience, service mesh observability, distributed tracing, and when microservices are premature.

8 min read·Feb 25, 2025

AI Rules for Hexagonal Architecture

AI wires logic directly to infrastructure. Rules for ports and adapters pattern, driving vs driven ports, primary and secondary adapters, hexagonal testability, and swappable infrastructure without domain changes.

7 min read·Feb 24, 2025

AI Rules for Clean Architecture

AI tangles business logic with frameworks and databases. Rules for dependency inversion, use case interactors, interface adapters, framework-independent domain, and testability through layer boundaries.

8 min read·Feb 23, 2025

AI Rules for Domain-Driven Design

AI builds anemic models with scattered logic. Rules for ubiquitous language, bounded contexts, aggregate boundaries, value objects, domain events, repository pattern, and anti-corruption layers between contexts.

8 min read·Feb 22, 2025

AI Rules for CQRS and Event Sourcing

AI uses one model for reads and writes. Rules for command/query separation, event store append-only logs, read model projections, snapshot optimization, temporal queries, and when CQRS is overkill.

8 min read·Feb 21, 2025

AI Rules for Event-Driven Architecture

AI chains synchronous calls for async workflows. Rules for event schemas, message queues (SQS, BullMQ), saga orchestration, dead letter queues for failures, idempotent consumers, and eventual consistency.

8 min read·Feb 20, 2025

AI Rules for Serverless Patterns

AI treats serverless like traditional servers. Rules for stateless function design, cold start mitigation, connection pooling strategies, idempotent operations, timeout handling, and cost-aware architecture.

8 min read·Feb 19, 2025

AI Rules for Edge Computing

AI deploys to one region ignoring edge runtimes. Rules for edge-compatible code patterns, middleware at the edge, data locality strategies, edge caching with stale-while-revalidate, and edge runtime constraints.

7 min read·Feb 18, 2025

AI Rules for Streaming SSR

AI blocks rendering until all data resolves. Rules for streaming HTML with React Suspense, progressive shell-first rendering, out-of-order streaming, TTFB optimization, and fallback loading strategies.

7 min read·Feb 17, 2025

AI Rules for React Server Components

AI marks every file 'use client' and fetches in useEffect. Rules for server-first component architecture, minimal client boundaries, server actions for mutations, Suspense streaming, and zero-waterfall data fetching.

8 min read·Feb 16, 2025

AI Rules for Micro-Frontends

AI builds monolithic frontends or splits at wrong boundaries. Rules for vertical domain slices, Module Federation, shared dependency management, event-bus communication, and independent deployment pipelines.

8 min read·Feb 15, 2025

AI Rules for Design System Components

AI builds one-off components with hardcoded colors. Rules for design token systems, variant-based component APIs, accessible primitive components, Storybook-driven development, and consistent API patterns.

8 min read·Feb 14, 2025

AI Rules for Component Architecture

AI builds 500-line god components. Rules for single responsibility, container/presentational split, composition over configuration, context for prop drilling, custom hooks for logic extraction, and file colocation.

8 min read·Feb 13, 2025

AI Rules for Animation Patterns

AI animates with JavaScript and ignores motion preferences. Rules for CSS transitions over JS animation, GPU-accelerated transform/opacity, Framer Motion, prefers-reduced-motion, and 60fps animation performance.

7 min read·Feb 12, 2025

AI Rules for Dark Mode Implementation

AI inverts colors for dark mode. Rules for CSS custom properties theming, prefers-color-scheme detection, localStorage persistence, WCAG contrast ratios in both themes, and semantic color token systems.

7 min read·Feb 11, 2025

AI Rules for Responsive Design

AI builds fixed-width desktop layouts. Rules for mobile-first CSS, fluid typography with clamp(), container queries, responsive image srcset, touch-friendly target sizes, and viewport meta configuration.

7 min read·Feb 10, 2025

AI Rules for Image Optimization

AI serves uncompressed PNGs at 4000px. Rules for WebP/AVIF format selection, responsive srcset with sizes, Next.js Image component, CDN image delivery, and automated compression in build pipelines.

7 min read·Feb 8, 2025

AI Rules for Lazy Loading

AI loads everything upfront. Rules for native image lazy loading, Intersection Observer for components, progressive data fetching, skeleton loading states, and fetchpriority hints for critical content.

7 min read·Feb 7, 2025

AI Rules for Code Splitting

AI ships one massive JavaScript bundle. Rules for route-based code splitting, dynamic imports, React.lazy with Suspense boundaries, vendor chunk optimization, and CI bundle size monitoring.

7 min read·Feb 6, 2025

AI Rules for Dependency Management

AI installs packages blindly. Rules for dependency audits, bundle size impact analysis, lockfile management, semantic versioning update strategies, and supply chain security with integrity checks.

7 min read·Feb 5, 2025

AI Rules for Secrets Rotation

AI hardcodes API keys and never rotates them. Rules for HashiCorp Vault and AWS Secrets Manager, automated rotation schedules, zero-downtime rollover, CI secret scanning, and leak incident response.

7 min read·Feb 4, 2025

AI Rules for Encryption at Rest

AI stores API keys and PII as plain text in the database. Rules for AES-256-GCM field-level encryption, KMS key management, envelope encryption, key rotation, and data classification policies.

8 min read·Feb 3, 2025

AI Rules for HTTPS and TLS

AI uses HTTP URLs and skips HSTS. Rules for TLS 1.3, HSTS preloading, automated certificate management with Let's Encrypt, HTTP-to-HTTPS redirects, and modern cipher suite configuration.

7 min read·Feb 2, 2025

AI Rules for Content Security Policy

AI ships zero CSP headers — any injected script runs freely. Rules for script-src with nonces, style-src, connect-src allowlists, frame-ancestors, CSP report-uri, and incremental rollout via report-only mode.

8 min read·Feb 1, 2025

AI Rules for CORS Configuration

AI sets CORS to allow-all origins. Rules for origin allowlists, credentials with specific origins, preflight cache optimization, exposed headers, and per-environment CORS configuration.

7 min read·Jan 31, 2025

AI Rules for Input Sanitization

AI interpolates user input into queries and templates with no sanitization. Rules for parameterized queries, context-aware output encoding, allowlist validation, and injection prevention across SQL, HTML, and OS commands.

8 min read·Jan 30, 2025

AI Rules for Data Serialization

AI returns raw database rows as API responses. Rules for DTO patterns, response shaping, ISO 8601 dates, consistent naming conventions, pagination envelopes, and never exposing internal IDs or fields.

7 min read·Jan 29, 2025

AI Rules for Error Codes and Messages

AI returns generic 500 errors for everything. Rules for structured error responses with machine-readable codes, user-facing messages, field-level validation errors, and docs links in error payloads.

7 min read·Jan 28, 2025

AI Rules for API Documentation

AI builds APIs with no documentation. Rules for OpenAPI/Swagger specs, request/response examples, error code catalogs, authentication docs, and auto-generated SDK documentation.

7 min read·Jan 27, 2025

AI Rules for API Versioning

AI builds APIs with no versioning — breaking changes break every client. Rules for URL path versioning, Accept header versioning, deprecation timelines, additive changes, and migration guides.

7 min read·Jan 26, 2025

AI Rules for Session Management

AI creates sessions with no expiration and client-only logout. Rules for Redis-backed sessions, idle and absolute timeouts, session regeneration on privilege change, and concurrent session limits.

7 min read·Jan 25, 2025

AI Rules for OAuth Integration

AI exposes client secrets in frontend code and skips CSRF protection. Rules for Authorization Code + PKCE, state parameter validation, secure token exchange, scopes, and account linking.

7 min read·Jan 24, 2025

AI Rules for JWT and Token Management

AI creates JWTs with no expiration stored in localStorage. Rules for RS256 signing, minimal claims, httpOnly cookie storage, refresh token rotation, token families, and revocation strategies.

8 min read·Jan 23, 2025

AI Rules for Authorization and RBAC

AI scatters role checks across every route handler. Rules for RBAC with permission hierarchies, ABAC policies, middleware-enforced authorization, and principle of least privilege.

8 min read·Jan 22, 2025

AI Rules for Authentication Flows

AI stores passwords in plain text and skips session invalidation. Rules for bcrypt hashing, JWT refresh rotation, MFA integration, OAuth flows, and secure session lifecycle.

8 min read·Jan 21, 2025

AI Rules for Form Validation

AI validates with if-statements and shows errors one at a time. Rules for Zod/Yup schema validation, React Hook Form, field-level errors, accessible error display, and server-side validation.

7 min read·Jan 20, 2025

AI Rules for Pagination Patterns

AI fetches all records then slices in JS. Rules for database-level pagination: cursor-based for APIs, offset with limits, keyset for performance, and infinite scroll implementation.

7 min read·Jan 15, 2025

AI Rules for GraphQL APIs

AI-generated GraphQL has N+1 resolvers, no pagination, and missing input validation. Rules for schema design, DataLoader batching, and query complexity limiting.

8 min read·Jan 8, 2025

AI Rules for Caching Strategies

AI caches nothing or caches everything with no invalidation. Rules for cache-aside pattern, TTL configuration, invalidation strategies, cache stampede prevention, and multi-layer caching.

8 min read·Nov 28, 2024

AI Rules for State Management

AI puts API data, form state, and UI toggles in one Redux store. Rules for server/client state separation, state colocation, derived state over redundant state, and choosing the right tool.

8 min read·Nov 20, 2024

AI Rules for Memory Management

AI creates memory leaks in every language. Rules for cleanup on unmount, WeakRef for caches, event listener removal, growing collection limits, and heap profiling with DevTools.

7 min read·Aug 15, 2024