GraphQL Client Platform
Custom Query AST Parser & Normalized Cache Client
1. Problem Statement
Standard GraphQL client libraries (Apollo/Relay) have large bundle sizes, and simple fetch calls lack caching, leading to duplicate queries and slow user transitions.
2. Business Context & Friction
Using a lightweight GraphQL client decreases bundle size, boosting performance on mobile devices while ensuring consistent state across views.
3. Learning Objectives
- Parse GraphQL query strings into structured AST trees
- Store resources in a normalized client-side cache by ID
- Build optimistic UI mutation updates with rollback capabilities
- Deduplicate matching requests in flight to save bandwidth
4. Functional Requirements
GraphQL AST Parser
must-haveCompile GraphQL queries into Abstract Syntax Trees (AST) to validate fields and resolve arguments.
Normalized Client Cache
must-haveFlatten query responses and store records in a cache map by ID (`typename:id`) to prevent data inconsistency.
Optimistic Mutations Engine
should-haveUpdate UI views instantly when mutations start, and rollback changes cleanly if the API returns an error.
Fragment Fields Compiler
should-haveSupport resolving nested GraphQL fragments to promote reusable component declarations.
5. Non-Functional Specifications
Performance
- •Core client library bundle size must remain under 8KB gzipped.
- •Parsing queries and matching cache nodes must take under 3ms.
Scalability
- •Normalized cache must handle up to 5,000 active nodes without slowing down UI lookups.
- •Support resolving nested query trees up to 10 levels deep.
Accessibility (A11y)
- •Include hooks that announce mutation progress and completion status to screen readers.
- •Ensure query loading views expose descriptive accessibility labels.
Security
- •Filter and escape query parameters to block injection attacks.
- •Manage auth headers securely using scoped middleware configurations.
Reliability & Fault Tolerance
- •Rollback optimistic UI changes cleanly if mutation API requests fail.
- •Auto-retry queries on network failures using exponential backoff schedules.
Observability & Telemetry
- •Expose diagnostic logs detailing cache hit rates and fetch times.
- •Export in-flight request deduplication metrics for analysis.
6. Core Modules Breakdown
Query AST Parser
Compiles GraphQL query strings into Abstract Syntax Trees (AST).
- •Tokenize GraphQL query strings
- •Build structured AST representations
- •Validate fields against schemas
Normalized Cache Store
Saves query records in a flattened map, keeping data consistent across views.
- •Flatten API responses into resource nodes
- •Query nodes by Typename and ID
- •Notify components when cached resources change
Request Deduplicator
Coordinates active requests in flight and forwards results to duplicate listeners.
- •Track active network requests
- •Group matching queries together
- •Broadcast response data to all subscribers
7. Key User Flows
User queries item data
- Component calls query client hook.
- Parser compiles query to AST; cache checks for matches.
- If found, the client returns cached data. If missing, it fetches the query and normalizes the response.
User submits optimistic mutation
- User updates post details.
- Client updates local cache instantly; views re-render with the new data.
- Mutations API requests are sent. If it fails, the client rolls back cache values to original state.
8. Architectural Blueprint
frontend Architecture
- •Lightweight TypeScript client library with custom React hooks wrappers.
- •Vite build tool configuration.
state Management
- •Custom normalized state store managing nodes maps.
- •Notify UI components when cached items update.
data Fetching
- •Standard POST requests sending query payloads to GraphQL gateways.
- •Dynamic request deduplication pipelines.
caching
- •Normalized in-memory cache.
- •Optionally save cache snapshots to localStorage.
routing
- •Compatible with all major routers; independent of routing layer.
deployment
- •Build and publish client package to NPM registry; host dashboard guides on Vercel CDN.
9. Component Execution Plan
| Component | Responsibility | Notes |
|---|---|---|
| QueryProvider | Main Context component containing client cache store instances. | Delivers cache access to child components. |
| useQuery | Custom hook that handles query parsing, caching, and fetch requests. | Subscribes to target cache changes. |
| useMutation | Custom hook that runs mutations and handles optimistic UI updates. | Runs rollback callbacks on failures. |
10. API Specifications
Send GraphQL queries and variables to the server gateway.
{
"query": "query GetUser($id: ID!) { user(id: $id) { id name } }",
"variables": { "id": "u1" }
}{
"data": {
"user": { "id": "u1", "name": "Alex" }
}
}11. Logical Data Schemas
CacheRecord
Schema mapping normalized client cache nodes.
12. Curriculum Milestones
Parser AST Development
- •Build GraphQL query tokenizer.
- •Write parsing functions to compile queries into AST trees.
Normalized Cache Store
- •Write cache normalizer flattening nested arrays.
- •Implement node query and update functions.
Request Deduplication
- •Build in-flight request deduplicator wrapper.
- •Implement query component cache subscription hooks.
Optimistic Mutations
- •Integrate useMutation hooks.
- •Build optimistic UI updates and rollback handlers.
API Reference Docs
- •Publish detailed API reference documentation.
- •Prepare system design interview explanations detailing cache normalization.
13. Technical Execution Roadmap
Write query tokenizer parser
Convert query strings into tokens arrays.
Create normalized store
Build data structures to flatten and store objects by ID.
Develop React query hook
Create hooks that fetch queries and manage loading states.
Build optimistic mutations UI
Implement write policies that update caches before APIs resolve.
14. Systems Interview Deep Dive
Elevator Pitch
“I built an 8KB GraphQL client with a custom query AST parser, a normalized cache store that flattens data, and an optimistic mutation engine that handles rollbacks cleanly.”
Architecture Summary
Queries are compiled into ASTs. API responses are flattened into a normalized cache map (keyed by `typename:id`). UI components subscribe to cache changes, re-rendering only when their data updates.
Architectural Tradeoffs
- ▲Building a custom parser limits support for complex schema variables, but it reduces package size by 85% compared to Apollo.
- ▲Normalized caches require unique object IDs, which we handle by requiring 'id' and '__typename' fields in queries.
Possible Follow-up Questions
- ?Explain how cache normalization works.
- ?How do you implement request deduplication for concurrent page queries?
15. Future Enhancements
- Add schema validation build scripts.
- Support offline mutation sync queues.
16. Future Integration Links
GitHub Repository
Access to source code files is planned for later.
Live Demo Application
Interactive live deployment sandbox environment.
Project Documentation
Detailed setup, guidelines and design patterns docs.