How do you optimize REST API performance — N+1 avoidance, sparse fieldsets, and response compression?

Answer

REST API performance optimization operates at multiple layers. N+1 query avoidance: use eager loading (SQL JOINs or ORM includes) when a list endpoint triggers per-item queries. For GET /posts that includes author data, load all posts then all authors in two queries instead of N+1. Sparse fieldsets (?fields=id,name): select only requested columns in SQL, skip serialization of omitted fields, reducing CPU and bandwidth. Response compression (gzip/brotli): enable at the reverse proxy layer — JSON compresses 70-90%. HTTP caching: set ETag and Cache-Control headers; responses served from CDN cache cost near-zero compute. Connection pooling: reuse database connections rather than creating new ones per request. Async processing: move expensive writes to background queues (Redis Queue, SQS), returning 202 immediately. Pagination: never return unbounded lists — enforce maximum page sizes. Database indexes: ensure all filter/sort columns are indexed. Response time budgeting: set p99 latency targets (e.g., 200ms) and measure per-endpoint with APM tools like Datadog or New Relic.