Resource Granularity Trade-offs
What you'll learn: How to decide between splitting your REST API into many small resources versus grouping them into fewer large ones.
When designing REST APIs, you face a choice: should /users/{id} include everything (name, email, address, preferences) in one response, or should address live at /users/{id}/address and preferences at /users/{id}/preferences?
Fine-Grained Resources
These are smaller, focused resources. They offer flexibility—clients fetch only what they need. A mobile app might only request /users/{id}/profile-picture to save bandwidth, while a dashboard might fetch /users/{id}/preferences.
Trade-off: More HTTP requests. A client needing user details, address, and preferences makes three separate calls. This increases latency (especially over slower networks) and adds complexity to client code.
Coarse-Grained Resources
These bundle related data together. One call to /users/{id} returns everything: name, address, preferences, recent activity.
Trade-off: Over-fetching. The mobile app gets a massive JSON payload when it only wanted the profile picture. This wastes bandwidth and processing time on both sides.
Finding Balance
Think of it like grocery shopping. Fine-grained resources are buying individual ingredients—flexible but requires multiple trips. Coarse-grained resources are buying a meal kit—convenient but you might not need everything inside.
Consider:
- Client needs: Do most clients need everything together?
- Network conditions: Are clients on slow connections?
- Data size: How big is each resource representation?
- Update patterns: Do these data pieces change independently?
Common approach: Start coarse-grained for data frequently used together. Offer fine-grained endpoints when clients consistently need only parts, or when sub-resources update independently (like /users/{id}/password).
Key Takeaway: Balance fine-grained resources (more flexibility, more requests) against coarse-grained resources (fewer requests, potential over-fetching) based on your clients' actual usage patterns and network constraints.