๐ก API Integration
๐ก 1. REST & Server-Sent Events (SSE)
Section titled โ๐ก 1. REST & Server-Sent Events (SSE)โWhile standard REST is the baseline, SSE is the Programmerโs secret weapon for โone-wayโ real-time updates.
- How it works: A standard HTTP connection that stays open. The server โpushesโ data to the client whenever an update occurs.
- Pros: Uses standard HTTP (easier to scale via load balancers); automatic reconnection; lighter than WebSockets for read-only streams.
- Best For: Live scoreboards, stock tickers, or notification feeds.
๐ 2. WebSockets (Bi-directional)
Section titled โ๐ 2. WebSockets (Bi-directional)โWhen you need full-duplex communication where both the client and server can talk at any time.
- The Protocol: Starts as an HTTP request and โupgradesโ to a persistent TCP connection (
ws://). - Programmer Challenges:
- State Management: Every open connection consumes server memory. You must handle โHeartbeatsโ (Pings/Pongs) to detect dead connections.
- Scalability: If you have multiple server instances, you need a Pub/Sub (like Redis) to broadcast messages between servers so a user on Server A can talk to a user on Server B.
- Best For: Chat apps, collaborative editing (Google Docs style), and multiplayer gaming.
๐ธ๏ธ 3. GraphQL (Declarative Data)
Section titled โ๐ธ๏ธ 3. GraphQL (Declarative Data)โGraphQL solves the โOver-fetchingโ and โUnder-fetchingโ problems of REST.
- Core Concepts:
- Queries: Ask for exactly what you need.
- Mutations: Change data on the server.
- Subscriptions: Real-time updates (usually implemented via WebSockets).
- Programmerโs Strategy: Use Fragments to keep your frontend code modular. A component should define the data it needs, and the parent โcomposesโ those fragments into a single query.
- The Trade-off: GraphQL moves complexity from the API to the Server (Schema design, Resolver optimization). Beware of the N+1 problem in resolversโuse a tool like
DataLoaderto batch requests.
๐ 4. Response Streaming (JSON & Fetch)
Section titled โ๐ 4. Response Streaming (JSON & Fetch)โModern browsers now support reading response bodies as a ReadableStream.
- The Use Case: Large datasets or AI responses (like ChatGPT). You donโt want to wait for a 2MB JSON to finish downloading before showing the first line to the user.
- Implementation: Using
ndjson(Newline Delimited JSON), the server sends one object at a time. The frontend processes each โchunkโ as it arrives.
๐ ๏ธ Implementation Patterns
Section titled โ๐ ๏ธ Implementation Patternsโ1. The Repository Pattern
Section titled โ1. The Repository PatternโNever call fetch or useQuery directly in your UI components with raw URLs.
- Programmerโs Move: Create an API Client Layer. Your components should call
UserService.getProfile(id), which hides whether that data comes from REST, GraphQL, or a local cache. This makes switching protocols or mocking for tests much easier.
2. Optimistic UI Updates
Section titled โ2. Optimistic UI UpdatesโDonโt make the user wait for the server to say โSuccess.โ
- Strategy: When a user clicks โLike,โ update the UI immediately. In the background, send the API request. If the request fails, roll back the UI state and show an error. Libraries like TanStack Query make this logic much simpler to manage.
3. Graceful Degradation
Section titled โ3. Graceful Degradationโ- Scenario: A WebSocket connection fails.
- Programmerโs Move: Implement a fallback mechanism. If the socket fails to connect after 3 tries, revert the app to Long Polling or standard REST fetches to ensure the user isnโt stuck.
๐ก Note: Before implementing WebSockets, ask: โDo I actually need real-time, or is a 30-second TTL in the cache enough?โ Real-time adds massive complexity to your infrastructure and debugging. Often, a well-tuned Cache-Aside strategy is better for 90% of use cases.