GraphQL and Flexible Query APIs Questions
Designing schema-driven query APIs where clients specify exactly the data they need. Covers schema and type design (queries, mutations, cursor pagination, nullability, interfaces and unions, mutation errors as typed data), resolvers, the N+1 problem and per-request DataLoader batching, federation with entity keys, query cost, depth and alias limiting, error handling and partial responses, persisted queries and caching, and evolving a shared schema through deprecation. Choosing between GraphQL and REST, REST-to-GraphQL migration, rate-limiting algorithms and API versioning schemes are covered elsewhere.
Design the GraphQL types for a product API where one client needs a lightweight product summary and another needs full variant and inventory detail. How do you model nullability, interfaces or unions, and mutation errors so generated client types stay accurate, and how do those choices affect performance and caching?
Sample Answer
The idea in plain words
In GraphQL the client chooses the fields, so a "summary" client and a "full detail" client do not need two APIs or two types: they need one well-shaped type where the cheap fields are cheap and the expensive fields are separate, opt-in fields. The hard part is the type system around that. Nullability (marking each field as "may be null" or "never null") decides how a failure spreads and what types a code generator produces. An interface (a set of fields several types share) or a union (a value that is one of several listed types) models products that differ in shape. Errors as data means expected failures of a mutation are returned as typed values in the response rather than only as entries in the generic errors list. Each choice trades client simplicity, schema flexibility and cacheability, so I decide each on purpose. Nullability and errors as data are the two decisions that most change the generated client code; interfaces or unions, and the caching choices, shape how the schema grows and how responses are reused.
Step 1: one product type, expensive parts as their own fields
A note on reading the listing: GraphQL has no inheritance between types, so every type that implements an interface must repeat each of the interface's fields with a compatible type. The repetition below is required by the language, not copy-paste noise.
interface Product {
id: ID!
name: String!
thumbnailUrl(width: Int = 160): String!
price: Money!
variants(first: Int = 10, after: String): VariantConnection! # detail clients only
}
type PhysicalProduct implements Product {
id: ID!
name: String!
thumbnailUrl(width: Int = 160): String!
price: Money!
variants(first: Int = 10, after: String): VariantConnection!
weightGrams: Int
}
type DigitalProduct implements Product {
id: ID!
name: String!
thumbnailUrl(width: Int = 160): String!
price: Money!
variants(first: Int = 10, after: String): VariantConnection!
downloadSizeBytes: Int
}
type Variant {
id: ID!
sku: String!
options: [OptionValue!]!
inventory: Inventory # nullable on purpose, see below
}
type Inventory { available: Int! warehouse: String! }
union AddToCartResult = AddToCartSuccess | OutOfStock | VariantNotFound
type AddToCartSuccess { cart: Cart! }
type OutOfStock { variantId: ID! available: Int! }
type VariantNotFound { variantId: ID! }
type Mutation { addToCart(variantId: ID!, quantity: Int!): AddToCartResult! }
# Cart, OptionValue, VariantConnection and VariantEdge (with node: Variant!) follow the usual
# connection shape and are omitted for space.
The summary client asks for id name thumbnailUrl price and never touches variants, so the server never runs the variant or inventory resolvers for it. The detail client adds variants { sku options inventory { available } }. One schema, two payload sizes, and nothing is computed that was not requested.
Here is what each client sends and receives, assuming a root field product(id: ID!): Product and illustrative data. The summary client:
{ product(id: "p1") { id name thumbnailUrl } }
{ "data": { "product": { "id": "p1", "name": "Trail bottle", "thumbnailUrl": "https://img.example.test/p1-160.jpg" } } }
The detail client adds an inline fragment (... on PhysicalProduct { ... }, a selection that applies only when the object is of that concrete type) and __typename (a built-in field that returns the object's concrete type name):
{ product(id: "p1") { __typename id name ... on PhysicalProduct { weightGrams } ... on DigitalProduct { downloadSizeBytes } } }
{ "data": { "product": { "__typename": "PhysicalProduct", "id": "p1", "name": "Trail bottle", "weightGrams": 240 } } }
The fragment for DigitalProduct contributes nothing here because this product is physical; the __typename value is what tells the client which fields to expect.
Step 2: nullability, decided field by field
Rule of thumb: non-null (!) means "the server can always produce this, or the whole parent is meaningless". Make a field nullable when it is backed by something that can fail independently.
id,name,priceare non-null: they come from the same row as the product, so if they are missing the product is genuinely broken.inventoryis nullable because it comes from a separate inventory service. If it times out, GraphQL sets that one field to null and reports an entry inerrors; the product and its variants still render. If it wereInventory!, a non-null field that errors makes its parent null, and the null keeps climbing to the nearest nullable ancestor.- Lists:
[OptionValue!]!means the list always exists and never contains null.[Variant]would force every client to check each element.
Worked propagation with the inventory service down for one variant (illustrative):
| Schema | What the client receives |
|---|---|
inventory: Inventory | that variant has inventory: null, plus one error at path product.variants.edges.0.node.inventory; all other fields intact |
inventory: Inventory! | the Variant becomes null; since VariantEdge.node is Variant!, the edge becomes null; with the usual connection shape edges: [VariantEdge!]!, the whole edges list becomes null, then the VariantConnection; and because Product.variants is VariantConnection!, the product itself becomes null. The null stops at the first nullable field above, here the root product(id: ID!) field, so data.product is null. One flaky dependency blanks the whole product, summary fields included |
The cost of too many nullable fields is on the client side: generated types for a nullable field are T | null (or an optional type) and every use needs a check. So I use ! for data that is truly guaranteed, and nullable for data with its own failure or permission rules. For an output field, changing nullable to non-null later is usually safe for readers, while changing non-null to nullable breaks generated client code that assumed a value. In generated types the difference is inventory: { available: number } | null before and inventory: { available: number } after: code that already checks for null keeps compiling when the type tightens, but code written against the non-null type crashes or fails to compile when the field loosens to nullable.
Step 3: interfaces, unions and generated types
Productis an interface because summary and detail clients share many fields and only some product kinds have extra fields (weightGrams,downloadSizeBytes). A client that needs the extras writes an inline fragment:... on PhysicalProduct { weightGrams }.- Code generators (build tools that read the schema and the client's queries and write typed client code) turn the abstract type into a discriminated union (a TypeScript-style type tagged by
__typename). For the detail query above, the generated type looks like this (illustrative):
type ProductDetail =
| { __typename: "PhysicalProduct"; id: string; name: string; weightGrams: number | null }
| { __typename: "DigitalProduct"; id: string; name: string; downloadSizeBytes: number | null };
Client code switches on __typename and the compiler knows which fields exist in each branch. That only stays accurate if clients always request __typename on abstract types, which most client libraries add automatically.
- Use an interface when the types share fields clients read uniformly; use a union when the members share nothing useful, as with the mutation result above. Adding a new member to a union or a new implementation of an interface is a change existing exhaustive client code may not handle, so I announce it and keep a default branch in clients.
Step 4: mutation errors as data
addToCart returns a union. Expected business outcomes (OutOfStock with how many are available, VariantNotFound) are typed members the client must handle; unexpected failures (database down, bug) still come back in the top-level errors list. The generated client type then forces the UI to handle OutOfStock explicitly, instead of parsing an error string.
Alternative: a payload object with a userErrors: [UserError!]! list (a code and a message per error). It is easier to extend (new codes do not change the type shape) but weaker typed. My choice here: a union for outcomes that carry different data and need distinct UI, and a userErrors list for plain field validation (quantity must be positive). Both are legitimate; what matters is picking one convention for the whole API.
Performance and caching effects
| Choice | Effect |
|---|---|
Separate variants / inventory fields | the summary query touches one table; the detail query adds batched variant and inventory loads (per-request DataLoader) |
Nullable inventory | a slow inventory service degrades one field; add a per-call timeout so it cannot hold the whole response |
thumbnailUrl(width:) | the server returns a right-sized image URL, so the client downloads fewer bytes |
| Persisted summary query served by GET | a persisted query is registered on the server ahead of time under an id, so the client sends only the id in a short GET URL; the full response can then be cached at a CDN (content delivery network, a cache close to users) |
Stable id on every object | a normalised client cache stores each object once under its type and id (for example PhysicalProduct:p1), so one mutation result updates that product everywhere on screen |
Caching detail: a response can only be cached for as long as its shortest-lived field. Assume summary fields are fine for 300 seconds and inventory for 5 seconds (assumed figures). A single query asking for both is cacheable for 5 seconds; keeping summary and inventory in separate operations lets the summary live 300 seconds. That is a concrete reason to keep volatile data (stock, live price) in its own field and its own query on the client.
Common mistakes
- One giant
ProductDetailtype plus a separateProductSummarytype with copied fields. It doubles maintenance; fields drift. - Marking everything non-null for neat generated types, then watching one failed dependency blank a page.
- Marking everything nullable, so clients are full of null checks and bugs hide in them.
- Returning errors only as strings in the
errorslist for expected cases, which forces clients to parse messages. - Hiding expensive data inside a cheap-looking field without a pagination limit or cost.
A GraphQL query that lists 50 orders with their customers triggers 51 database queries. Explain why this happens, how you would confirm it, and how you would fix it.
Sample Answer
The idea in plain words
GraphQL runs a resolver (a small function that produces the value of one field) once for every object that has that field. A list of 50 orders is fetched by one resolver on Query.orders. Each order then needs its customer, and the Order.customer resolver runs once per order, each time issuing its own database query. That is 1 query for the list plus 50 for the customers: 51. This is the N+1 problem (one query for the parent list, then N more, one per parent). Nothing is wrong with any single resolver; the cost comes from many tiny, independent resolvers that cannot see each other.
The fix is to let the resolvers of one request pool their needs: collect the 50 customer ids, ask the database once, and hand each resolver its own answer. That is what a DataLoader (a small per-request batching and caching helper) does, and the alternatives are a join or a look-ahead in the parent resolver.
Why it happens, step by step
Assume this query and a schema where Order.customer is resolved by a function that runs SELECT ... FROM customers WHERE id = $1:
{
orders(first: 50) {
id
total
customer { id name }
}
}
- The
ordersresolver runsSELECT id, total, customer_id FROM orders ORDER BY id LIMIT 50. That is query number 1. - The executor (the part of the GraphQL server that walks the query and calls resolvers) now has 50 order objects. For each one it must complete the
customerfield, so it calls theOrder.customerresolver 50 times, each with a different parent. - Each call does not know that 49 siblings are asking the same kind of question, so each sends its own
SELECT ... WHERE id = $1. That is queries 2 to 51.
The database log for the request looks like this (illustrative, with assumed ids):
SELECT id, total, customer_id FROM orders ORDER BY id LIMIT 50
SELECT id, name FROM customers WHERE id = 17
SELECT id, name FROM customers WHERE id = 4
SELECT id, name FROM customers WHERE id = 17
... 47 more single-row lookups
Note the repeated id = 17: the naive version even asks twice for a customer who placed two of the orders.
How to confirm it (in the order I would check)
- Count queries per request. Add a counter in the database layer (or the ORM, object-relational mapping, hook; an ORM is a library that turns objects into SQL) keyed by request id and log it next to the operation name. A request fixed with a loader shows 2 (one query for the orders, one batched query for the customers); a join, whether written directly in the parent resolver or produced by a look-ahead, shows 1; the broken one shows 51.
- Read the repeated statement. Turn on the database's statement log (a server setting that writes every executed SQL statement to a file) for one request. Fifty statements that differ only in the id literal are the signature.
- Check that it scales with the page size. Call with
first: 10, thenfirst: 50. N+1 gives 11 then 51 queries (query count = 1 + page size). A loader (batch) gives 2 both times, and a join (direct or via look-ahead) gives 1 both times. - Look at a trace. A distributed trace is a timeline of one request, recorded as nested spans (one span is a timed step, such as one resolver or one database call). In a trace viewer the request shows one
ordersspan followed by a row of 50 short, near-identical database spans underOrder.customer, like the teeth of a comb. - Pin it with a test. Add an integration test that runs this operation against a test database and asserts the query count is the small fixed number your fix gives (2 with a loader), whatever the page size. This catches a regression when someone adds a new nested field.
The fix
Preferred: a per-request DataLoader on customers. In the Order.customer resolver call customerLoader.load(order.customerId) instead of querying. The loader gathers every load call made in the same tick and calls one batch function with the distinct ids. A tick is one pass of the event loop, the scheduler that runs a server's queued work one piece at a time (in Node.js, the loader dispatches right after the current synchronous work and promise callbacks finish). The executor calls all 50 Order.customer resolvers back to back inside one such pass, so the loader sees all 50 load calls before it dispatches. The batch function then runs SELECT ... FROM customers WHERE id = ANY($1), where $1 is a placeholder bound to an array of ids and ANY is true when the row's id equals any element of that array, so one statement carries all 31 ids. It must return results in the same order as the keys, and it caches by key for the rest of the request. The loader is created fresh for every request (put it in the per-request GraphQL context, an object the server builds fresh for each incoming request and passes to every resolver), never shared between requests.
Worked count with an assumed data set: the 50 orders belong to 31 distinct customers.
| Version | Queries | Rows asked for |
|---|---|---|
| Naive resolvers | 1 + 50 = 51 | 50 single-row lookups, 19 of them repeats |
| DataLoader | 1 + 1 = 2 | one lookup carrying 31 distinct ids (50 - 19 = 31) |
Latency under an assumed 2 ms per query and a connection pool of 10 (assumptions, not measurements): the 50 lookups run in ⌈50/10⌉=5 rounds, so the request takes about 2+5×2=12 ms of database time against 2+2=4 ms batched, and the naive version also holds the whole pool busy, which slows other requests.
What the two alternatives look like. A join moves the customer lookup into the parent resolver's own statement, so the orders and their customers arrive together:
SELECT o.id, o.total, c.id AS customer_id, c.name
FROM orders o JOIN customers c ON c.id = o.customer_id
ORDER BY o.id LIMIT 50;
A look-ahead inspects the incoming query before running the parent resolver: if the selection includes customer, the orders resolver issues the join above, and if it does not, it skips the join. Either way the data for all 50 orders comes back in the parent's one statement, and the Order.customer resolver just reads it from the parent object.
Alternatives and when I would pick them:
| Option | Use when | Drawback |
|---|---|---|
Join in the parent resolver (orders JOIN customers) | the nesting is fixed and always requested | fetches customers even when the client did not ask for them, and couples the parent resolver to the child's table |
| Look-ahead (read the requested sub-fields from the query and prefetch) | one hot, known path | easy to get wrong with fragments and aliases; more code per field |
| DataLoader | the general case, any depth, fields requested conditionally | batches only calls in the same tick; needs the batch function to reorder results |
Common mistakes
- Creating one DataLoader at process start. Its cache then outlives the request: stale data and, for permission-dependent fields, one user's data served to another.
- A batch function that returns rows in the database's order instead of the keys' order, so customers are attached to the wrong orders.
- "Fixing" it by caching in the resolver with a process-wide map. That hides the symptom for hot ids and adds an invalidation problem.
- Batching the customer but not the next level (customer's address), which just moves the N+1 one level down. Check the query count again after every new nested field.
A mobile app talks to a GraphQL API and users on slow networks complain about load times and data usage, while server cost is rising. What would you change on the client and the server to cut bandwidth and cost, and what are the drawbacks of each change?
Sample Answer
The idea in plain words
Slow-network complaints and a rising server bill have the same root: the app and the server move and compute more than the screen needs. GraphQL helps because the client names the fields it wants, but only if the queries are actually trimmed, repeated work is cached, and the server stops re-parsing and re-fetching what it has seen before. I would first measure where the bytes and the server time go, then make seven changes, and for each one name what it costs. The changes fall into three groups: what the app asks for and keeps (1 to 3), how requests and responses travel (4 to 6), and the work the server does (7). The mobile developer owns the first group and negotiates the others with the server team. The seven are: trim the fields and image sizes, use smaller pages, set client cache policies, send persisted queries, compress responses, cache public queries at the edge, and batch plus cost-limit on the server.
Step 1: measure before changing anything
- Bytes per operation. Log, per operation name and app version, the request size, the response size (before and after compression) and how often it is called. Rank by response bytes×calls per day to find the three or four operations that matter.
- Experience on a bad network. Time the top screens on a throttled connection in a test device, and record the number of round trips each screen needs.
- Server cost per operation. Database queries per request, database time and CPU per operation, so you know whether cost is parsing, resolvers or the database.
Step 2: the seven changes and their drawbacks
| # | Change | Where | What it saves | Drawback |
|---|---|---|---|---|
| 1 | Ask only for the fields the screen renders (keep each component's fields in its own fragment), and request images at the size shown, for example imageUrl(width: 320) | client, plus one schema argument | response bytes, image bytes | more distinct query shapes to maintain, so more cache entries; image sizes need server support |
| 2 | Smaller pages with cursors (first: 20), load more on scroll | client and server | first-screen bytes and time | more round trips on a slow network; mitigate by prefetching the next page when the user nears the end |
| 3 | Client cache policy: a normalised cache (stores objects by type and id), cache-first reads (show the stored copy without asking the server unless it is missing or expired) for slow-changing screens, mutation payloads that return the changed fields | client | repeat requests and bytes | stale data; need explicit refresh rules; the cache takes device storage |
| 4 | Persisted queries: the server registers each query ahead of time, and the app sends a short hash of it instead of the full text | client and server | request bytes and server parse and validate work | build step to register queries; the server must keep old queries for old app versions that are still installed |
| 5 | Compress responses (the client sends Accept-Encoding, the server answers with Content-Encoding) | server or proxy | response bytes | CPU on the server (mitigated by compressing at the edge); little gain on tiny or already-compressed payloads such as images |
| 6 | Cache public, non-personalised queries at a content delivery network (CDN) | edge | origin requests, latency | staleness up to the time-to-live (TTL); cannot be shared for per-user data |
| 7 | Batch resolver database calls with a per-request DataLoader (it collects the lookups that resolvers make during one request into a single database query), and apply query cost limits (refuse a query whose estimated number of returned objects is above a ceiling) | server | database queries, server cost | tiny wait to collect a batch; legitimate heavy queries may need an exception |
Worked numbers (every input is an assumption, shown with its arithmetic)
The numbers below come from one program. It builds a 20-item home feed with assumed item fields, a short HomeFeed query, and the persisted-query request in both forms, then prints the byte counts. Item text is synthetic and repetitive, so its compression ratio is higher than real catalogue text would give; use the sizes as a worked example, not as typical savings.
import gzip
import hashlib
import json
from urllib.parse import quote
QUERY = """query HomeFeed($first: Int!, $after: String) {
feed(first: $first, after: $after) {
edges { node { id title imageUrl(width: 320) price { amountCents currency } } }
pageInfo { hasNextPage endCursor }
}
}"""
variables = {"first": 20, "after": None}
def compact(obj):
return json.dumps(obj, separators=(",", ":"))
# Persisted queries: the same request with the text, and with the hash
digest = hashlib.sha256(QUERY.encode()).hexdigest()
ext = {"persistedQuery": {"version": 1, "sha256Hash": digest}}
with_text = compact({"operationName": "HomeFeed", "variables": variables, "query": QUERY})
with_hash = compact({"operationName": "HomeFeed", "variables": variables, "extensions": ext})
url = ("/graphql?operationName=HomeFeed&variables=" + quote(compact(variables), safe="")
+ "&extensions=" + quote(compact(ext), safe=""))
print("query text bytes:", len(QUERY.encode()))
print("sha256 hex:", digest, "| length:", len(digest))
print("POST body with text:", len(with_text.encode()), "bytes | with hash:", len(with_hash.encode()), "bytes")
saved = len(with_text.encode()) - len(with_hash.encode())
print("saved per request:", saved, "| over 30 requests:", 30 * saved)
print("GET url characters:", len(url))
print(url)
# Response size: whole item objects versus only what the card renders
WORDS = ["light", "sturdy", "compact", "travel", "daily", "ceramic", "folding", "quiet", "bright", "recycled"]
items = []
for i in range(20):
desc = " ".join(WORDS[(i * 3 + j * 7) % 10] for j in range(40))
items.append({
"id": f"item-{i:02d}", "title": f"Item {i:02d} {WORDS[i % 10]}", "subtitle": WORDS[(i + 3) % 10] + " edition",
"description": desc, "imageUrl": f"https://img.example.test/{i:02d}-320.jpg",
"price": {"amountCents": 1000 + 37 * i, "currency": "USD"},
"seller": {"id": f"s{i % 5}", "name": f"Seller {i % 5}", "rating": 4.5},
"tags": [WORDS[i % 10], WORDS[(i + 1) % 10], WORDS[(i + 2) % 10]], "createdAt": f"2026-03-{i + 1:02d}T09:00:00Z",
})
cards = [{k: it[k] for k in ("id", "title", "imageUrl", "price")} for it in items]
full_b, card_b = len(compact(items).encode()), len(compact(cards).encode())
print("full items bytes:", full_b, "| card fields only:", card_b, "| saved:", full_b - card_b,
"| percent:", round(100 * (full_b - card_b) / full_b, 1))
full_gz = len(gzip.compress(compact(items).encode(), mtime=0))
card_gz = len(gzip.compress(compact(cards).encode(), mtime=0))
print("gzip full:", full_gz, "| gzip card fields only:", card_gz)
Output:
query text bytes: 214
sha256 hex: f4ab68046cbf649b02be120679dacf7f715c76fdae7b98598146491820db5f12 | length: 64
POST body with text: 296 bytes | with hash: 192 bytes
saved per request: 104 | over 30 requests: 3120
GET url characters: 241
/graphql?operationName=HomeFeed&variables=%7B%22first%22%3A20%2C%22after%22%3Anull%7D&extensions=%7B%22persistedQuery%22%3A%7B%22version%22%3A1%2C%22sha256Hash%22%3A%22f4ab68046cbf649b02be120679dacf7f715c76fdae7b98598146491820db5f12%22%7D%7D
full items bytes: 11861 | card fields only: 2745 | saved: 9116 | percent: 76.9
gzip full: 871 | gzip card fields only: 422
Trimming fields (change 1). The whole item object (title, subtitle, a 40-word description, seller, tags and dates as well as the card fields) is 11,861 bytes for 20 items. The card renders only id, title, imageUrl and price: 2,745 bytes. Saved: 11861−2745=9116 bytes, which is 9116/11861≈76.9% of the response before compression.
Compression (change 5). On the same data, gzip reduces the full response to 871 bytes and the trimmed one to 422 bytes. Trimming still saves 871−422=449 bytes after compression, so the two changes add up rather than replace each other.
Persisted queries (change 4). The HomeFeed query text is 214 bytes. A POST body carrying the text, the operation name and the variables is 296 bytes. With a hash the same request is 192 bytes: a SHA-256 hash written in hexadecimal is always 64 characters, wrapped as "extensions":{"persistedQuery":{"version":1,"sha256Hash":"..."}}. Saved per request: 296−192=104 bytes, and a session with 30 such requests saves 30×104=3,120 bytes of upload. The hashed body has a fixed size, so the saving grows with the query: a real screen with several nested fragments is longer than this 214-byte query, and every extra byte of query text is saved on every request. The server also looks up a pre-validated query by hash instead of parsing and validating text on every call.
Persisted queries are a convention layered on top of GraphQL, not part of the GraphQL specification; the field names (persistedQuery, sha256Hash) follow a widely used convention and your server may differ. As a GET, the request is cacheable by intermediaries. Illustrative exchange (the hash is the SHA-256 of the 214-byte HomeFeed query above, printed by the program):
GET /graphql?operationName=HomeFeed&variables=%7B%22first%22%3A20%2C%22after%22%3Anull%7D&extensions=%7B%22persistedQuery%22%3A%7B%22version%22%3A1%2C%22sha256Hash%22%3A%22f4ab68046cbf649b02be120679dacf7f715c76fdae7b98598146491820db5f12%22%7D%7D HTTP/1.1
Host: api.example.test
Accept: application/json
Accept-Encoding: gzip, br
HTTP/1.1 200 OK
Content-Type: application/json
Content-Encoding: gzip
Cache-Control: public, max-age=60
Vary: Accept-Encoding
Field meanings: operationName, variables and extensions are the places the GraphQL over HTTP specification (still a draft) puts those parts when the request is a GET; Accept-Encoding lists the compressions the app can decode; Content-Encoding: gzip says which one was used; Cache-Control: public, max-age=60 lets a CDN keep the response for 60 seconds (only correct for public data); Vary: Accept-Encoding tells caches that the stored copy depends on that request header. The URL is 241 characters here (also printed by the program), so large variables should switch to POST because URL length limits exist. If the server does not know the hash (for example after a cache flush or an unregistered query), it answers with an error and the app resends the full text once; strict "allowlist" setups refuse unknown queries instead.
Edge caching (change 6). If 40 of every 100 identical public requests are answered by the CDN (an assumed hit ratio), the origin sees 60 of every 100, a 40% reduction in origin work for those requests. Personalised queries, anything sent with a user's credentials, should be marked Cache-Control: private or no-store and are not part of this saving.
What I would do first, and what would change the order
My order: 1 and 2 (trim and paginate, no infrastructure), then 4 (persisted queries, because they cut upload bytes and server parsing and unlock 6), then 5 and 6, with 3 tuned per screen and 7 whenever the measurements show database time dominating. If the data is mostly personalised (no public cache hits) I would drop 6 and invest in 3 and 7. If the payloads are mostly images, change 1's image sizing outweighs the rest. For the first-screen delay specifically, some servers and clients support deferring non-critical parts of a response (the @defer directive for incremental delivery: a part of the query marked @defer is sent in a later chunk of the same response, so the main content can render first); that support is not universal, so confirm it on both ends before relying on it.
Common mistakes
- Optimising the query text while images are 80% of the bytes.
- Persisting queries without a plan for old app versions, which breaks users who have not updated.
- Caching a personalised response at the CDN because the URL looked the same. The cache key must include everything the response depends on.
- Making pages so small that a slow network pays latency for ten round trips instead of one.
- Enabling compression for everything, including already-compressed images, and paying CPU for nothing.
Running the code
Save the listing as payload.py and run it with Python 3.12 (standard library only):
python payload.py
Implement a minimal DataLoader-style batcher in Node.js (or any language) that collects user lookups issued in the same tick into one batched fetch, returns results in the order of the requested keys, and caches within a single request. Where do you create it, and what goes wrong if it is shared across requests?
Sample Answer
The idea in plain words
A DataLoader is a small helper that sits between GraphQL resolvers (the functions that fetch each field) and the database. Instead of every resolver asking for its own row immediately, each one calls load(key) and gets back a promise (a placeholder for a value that arrives later; Python calls it a future). The loader waits until the current tick (one turn of the event loop, the scheduler inside a Node.js or Python asyncio program that runs queued callbacks one at a time: the running code finishes and control returns to the scheduler) is over, then makes one call to a batch function with all the keys collected so far, and hands each caller its own value. This turns the N+1 problem (one query for a list, then N more, one per item) into two queries. The three promises it must keep: one batch call per tick, results returned in the order of the keys asked for, and a cache that lives for one request only.
Approach
load(key)checks the cache. If the key was already requested in this request, return the same promise (this also removes duplicates from the batch).- Otherwise create a promise, remember it in the cache, and append the key to a queue.
- The first key queued in a tick schedules one dispatch for the end of the tick (here
loop.call_soon; in Node.js the equivalent isprocess.nextTickor a microtask viaPromise.resolve().then). A microtask is a callback queued to run as soon as the current JavaScript code finishes, before the event loop moves on to timers or input and output;process.nextTickis Node.js's own queue with the same purpose, drained before promise callbacks. - At dispatch, take the queued keys, call
batch_fn(keys)once, check that it returned exactly one value per key in the same order, and resolve each promise with its value. - If the batch function fails, reject the promises of that batch and drop them from the cache so a later call can retry instead of replaying the failure.
The batch function has a contract that is the most common source of bugs: given [3, 1, 2, 9, 77] it must return five values in that order, using None (or an error object for that key) for an id that has no row. A database WHERE id = ANY(...) returns rows in its own order and silently omits missing ids, so the batch function must rebuild the order from a dictionary.
Why the dispatch lands after every load call of the tick
The key line is loop.call_soon(callback): it does not run callback now, it only appends it to the loop's ready queue, and the loop will not look at that queue until the currently running code yields control. In the demo, asyncio.gather(*(loader.load(k) for k in keys)) runs like this:
- The generator calls
loader.load(3), thenload(1),load(3)and so on, one after another, with noawaitbetween them, so the loop gets no chance to run anything else. The first call setsscheduled = Trueand queues the dispatch callback; the later calls only append keys. - All seven
loadcalls return their futures;gathercollects them and the code reachesawait. Only now does control return to the loop. - The loop runs the queued callback, which wraps
_dispatch()in a task (ensure_future) that runs on the next loop turn. By then the queue holds all five distinct keys, sobatch_fnis called once.
A load call made after an await that yielded to the loop would land in the next batch, which is the effect described under the edge cases below.
Python and Node.js names side by side.
| Python asyncio (used here) | Node.js equivalent | What it does |
|---|---|---|
loop.create_future() | new Promise((resolve, reject) => ...), keeping resolve and reject | the placeholder handed to one caller |
loop.call_soon(cb) | queueMicrotask(cb) or process.nextTick(cb) | run cb once the current code finishes |
asyncio.ensure_future(coro) | calling an async function, which starts it and returns a promise | start the dispatch coroutine |
asyncio.gather(*futs) | Promise.all(promises) | wait for every caller's value |
fut.set_result(v) / fut.set_exception(e) | resolve(v) / reject(e) | complete one caller's placeholder |
The structure (cache map, queue array, a scheduled flag, dispatch that zips values to placeholders) is the same in either language.
The code
import asyncio
# ---- The batcher (everything the technique needs) ----
class Batcher:
"""Collects load(key) calls made in the same event-loop tick into one batch_fn(keys) call."""
def __init__(self, batch_fn):
self.batch_fn = batch_fn
self.cache = {} # key -> Future; lives as long as this Batcher
self.queue = [] # keys waiting for the next dispatch
self.scheduled = False
def load(self, key):
if key in self.cache: # cache hit: same key, same Future
return self.cache[key]
loop = asyncio.get_running_loop()
fut = loop.create_future()
self.cache[key] = fut
self.queue.append(key)
if not self.scheduled: # first key of this tick schedules ONE dispatch
self.scheduled = True
loop.call_soon(lambda: asyncio.ensure_future(self._dispatch()))
return fut
async def _dispatch(self):
keys, self.queue, self.scheduled = self.queue, [], False
futs = [self.cache[k] for k in keys]
try:
values = await self.batch_fn(keys)
if len(values) != len(keys): # contract: one value per key, same order
raise RuntimeError(f"batch_fn returned {len(values)} values for {len(keys)} keys")
for fut, value in zip(futs, values):
fut.set_result(value)
except Exception as exc:
for k in keys:
del self.cache[k] # a failure is not cached
for fut in futs:
fut.set_exception(exc)
# ---- Demo scaffolding: a fake users table and two batch functions ----
DB = {1: "Ada", 2: "Bo", 3: "Cy", 9: "Di"} # users table: id -> name
CALLS = [] # every database round trip, as the list of ids sent
async def fetch_users_rows(ids):
"""Stand-in for: SELECT id, name FROM users WHERE id = ANY(ids).
Like a real database it returns rows in its own order and omits ids that do not exist."""
CALLS.append(list(ids))
return [(i, DB[i]) for i in sorted(set(ids), reverse=True) if i in DB]
async def batch_users(ids):
rows = dict(await fetch_users_rows(ids))
return [rows.get(i) for i in ids] # re-order to the keys' order; None for a missing id
async def batch_users_wrong(ids):
rows = await fetch_users_rows(ids)
return [name for _, name in rows] # BUG: keeps the database's order
# ---- Demo scenarios: batching, ordering, request-scoped cache, sharing mistakes ----
async def run(batch_fn, keys):
CALLS.clear()
loader = Batcher(batch_fn)
got = await asyncio.gather(*(loader.load(k) for k in keys))
return list(got), list(CALLS)
async def main():
keys = [3, 1, 3, 2, 1, 9, 77] # duplicates and one id (77) that does not exist
expected = [DB.get(k) for k in keys] # independent recomputation straight from the table
got, calls = await run(batch_users, keys)
print("naive calls would be:", len(keys), "| batched calls:", len(calls), "| keys sent:", calls[0])
print("result :", got)
print("expect :", expected)
print("check :", "ok" if got == expected else "FAIL")
keys4 = [3, 1, 2, 9] # all exist, so the lengths match and only the order is wrong
got, _ = await run(batch_users_wrong, keys4)
expected4 = [DB.get(k) for k in keys4]
print("wrong-order batch_fn result:", got)
print("check :", "ok" if got == expected4 else "FAIL")
loader = Batcher(batch_users)
CALLS.clear()
await asyncio.gather(loader.load(1), loader.load(2)) # tick one: one database call
await loader.load(1) # later tick, same loader: cache hit
print("same-request second read of id 1, extra calls:", len(CALLS) - 1)
# Sharing one loader across requests: request A warms it, then the row changes, then request B reads.
shared = Batcher(batch_users)
await shared.load(1)
DB[1] = "Ada Lovelace" # another request updates the row
stale = await shared.load(1) # request B reuses the shared loader
fresh = await Batcher(batch_users).load(1) # request B with its own loader
print("shared loader returns:", stale, "| per-request loader returns:", fresh)
# Same mistake with a per-viewer rule: the loader closes over who asked first.
EMAILS = {1: "ada@example.test"}
def make_email_loader(viewer_is_admin):
async def batch_emails(ids):
return [EMAILS.get(i) if viewer_is_admin else None for i in ids]
return Batcher(batch_emails)
admin_loader = make_email_loader(True)
print("admin reads email:", await admin_loader.load(1))
print("non-admin through the admin's shared loader:", await admin_loader.load(1))
print("non-admin through its own loader:", await make_email_loader(False).load(1))
asyncio.run(main())
Output:
naive calls would be: 7 | batched calls: 1 | keys sent: [3, 1, 2, 9, 77]
result : ['Cy', 'Ada', 'Cy', 'Bo', 'Ada', 'Di', None]
expect : ['Cy', 'Ada', 'Cy', 'Bo', 'Ada', 'Di', None]
check : ok
wrong-order batch_fn result: ['Di', 'Cy', 'Bo', 'Ada']
check : FAIL
same-request second read of id 1, extra calls: 0
shared loader returns: Ada | per-request loader returns: Ada Lovelace
admin reads email: ada@example.test
non-admin through the admin's shared loader: ada@example.test
non-admin through its own loader: None
Reading the output
- Seven
loadcalls (with the duplicates 3 and 1 and the missing id 77) produced one database call, which carried the five distinct keys[3, 1, 2, 9, 77]once each, and every caller received the value for its own key. The independent recomputationexpectis read straight from the table, not through the loader, and thecheckline compares the two. - The
wrong-orderlines show why the contract matters: a batch function that returns the database's order producedDi, Cy, Bo, Adafor the keys[3, 1, 2, 9], and the check printsFAIL. When a missing id is in the key list the same mistake usually surfaces as a length mismatch, which the dispatcher rejects with an error. - Reading id 1 again later in the same request made no extra database call: that is the per-request cache.
Where to create it, and what goes wrong if it is shared
Create the loaders once per incoming request, in the GraphQL context (the object built for each request and passed to every resolver), for example context.loaders = { users: new Loader(batchUsers) }. Then all resolvers of that request share the batching window and the cache, and everything is discarded when the request ends.
If one loader is created at process start and shared across requests, three things go wrong, and the output shows the first two:
- Stale data. The cache never expires, so after another request changed user 1 the shared loader still returned
Adawhile a per-request loader returnedAda Lovelace. - Data leaks between users. Any rule that depends on who is asking (a field only admins may see) gets baked into whatever the first caller cached. The non-admin read through the admin's shared loader returned the email; through its own loader it got
None. The batch function often closes over the viewer's identity, so sharing the loader shares one user's permissions. - Unbounded memory and mixed batches. The cache grows with every key ever seen, and keys from unrelated requests land in the same batch, so one slow or failing request can delay or fail the others.
A process-wide cache can still be right for slow-changing, non-personalised data, but it should be an explicit cache with a time-to-live and invalidation, placed behind the loader's batch function, not the loader itself.
Complexity and edge cases
- For n
loadcalls with d distinct keys in one tick: n cache lookups, one batch call with d keys, and building the key-to-row dictionary is O(d) (work grows in proportion to the number of distinct keys), so the dispatch is O(d) plus the database's own cost. Memory is O(d) for the request. In the demo, n=7 and d=5. - Duplicates: handled by the cache, so the batch sees each key once.
- Missing keys: return
None(or a per-key error object) at that position; do not shorten the list. - Batch size: a database may limit the number of parameters, so a production loader splits very large key lists into chunks (this demo does not).
- Keys that are not primitives (objects) need a cache-key function: a function that turns the key into a string, for example the JSON text of its fields, so two equal-looking objects hit the same cache entry.
- Keys requested after the tick has dispatched go into the next batch: a resolver that awaits something before calling
loadcan split what you hoped would be one batch. Check the batch count in a test. - The list above separates into correctness hazards (the batch function's ordering and missing-key contract, key identity, and a stray
awaitbeforeloadsplitting a batch) and production refinements. A library loader adds the refinements: chunking, error objects per key, cache priming (pre-filling the cache with a row you already hold, for example one a mutation just returned, so a laterloadskips the database) and cache clearing after a write.
Running the code
Save the listing as batcher.py and run it with Python 3.12 (standard library only, no install step):
python batcher.py
You are building a GraphQL layer that resolves fields by calling several backend REST services. When one backend fails or times out partway through a query, what does the client receive? Explain how GraphQL errors and partial data work, how null propagates through the schema, and how you would batch and cache downstream calls per resolver.
Sample Answer
The idea in plain words
A GraphQL response can be partly good. The server runs each field's resolver separately. If one resolver fails, the spec does not throw the whole response away: the failed field becomes null, an entry describing the failure is added to a top-level errors list, and every field that succeeded is still returned in data. The one twist is the schema's nullability (whether a field is allowed to be null). If the failed field is declared non-null (!), a null is not allowed there, so the null moves up to the parent, and keeps moving up until it reaches a field that may be null. So the client receives anything from "everything except one field" to "no data at all", and which one depends on how the schema was marked. Over HTTP this usually arrives as a success status with the errors inside the body, so clients and monitoring must read the body, not only the status code.
What the client receives: a worked case
Assumptions for the scenario (labelled, not facts about any real system): the GraphQL layer resolves Query.order from an orders REST service (120 ms), then Order.shipment from a shipping REST service and Order.customer from a customers REST service. The shipping call has a timeout of 800 ms and the shipping service does not answer in time. Client query:
{ order(id: 7) { id status shipment { eta carrier } customer { name } } }
shipment begins at character 28 of the single line ({ order(id: 7) { id status is 27 characters), so the error location is line 1, column 28. Sibling fields (shipment and customer) are typically resolved in parallel for a query, so the time to respond is about the orders call plus the longer of the two: 120+max(800,90)=920 ms (with an assumed 90 ms for the customer call).
The three cases below differ only in which fields carry !. The schema fragment (assumed) is:
type Query { order(id: ID!): Order } # Case A and B: nullable. Case C: Order!
type Order {
id: ID!
status: String!
shipment: Shipment # Case A: nullable. Case B and C: Shipment!
customer: Customer # nullable: separate backend
}
Case A: shipment: Shipment is nullable. Illustrative response:
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 258
{"data":{"order":{"id":"7","status":"PAID","shipment":null,"customer":{"name":"Ava"}}},"errors":[{"message":"Shipping service timed out after 800 ms","locations":[{"line":1,"column":28}],"path":["order","shipment"],"extensions":{"code":"UPSTREAM_TIMEOUT"}}]}
Read it field by field: data holds everything that worked; shipment is null; the single errors entry has a human message, locations (where in the query text), path (response path to the failed field, a list of field names and list indexes), and extensions (a free-form object where servers put machine-readable codes; the code name here is my own). Content-Length: 258 is the byte count of that body.
Case B: shipment: Shipment! is non-null, and order: Order is nullable. The null cannot sit at shipment, so it moves to order. The customer data that was fine is lost too:
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 194
{"data":{"order":null},"errors":[{"message":"Shipping service timed out after 800 ms","locations":[{"line":1,"column":28}],"path":["order","shipment"],"extensions":{"code":"UPSTREAM_TIMEOUT"}}]}
Case C: both shipment and order are non-null. Nothing nullable remains below the root, so the whole data becomes null: {"data":null,"errors":[...]} (184 bytes with the same error entry).
Two points to state precisely. First, the errors entry keeps the path of the field that actually failed (order.shipment), even when the null lands higher. Second, the GraphQL specification says that only when the request fails before execution (a syntax error, a validation error such as an unknown field) is there no data entry at all; failures during execution come with a data entry (possibly null). Status code practice varies: with the traditional application/json response, servers commonly return 200 for any request that reached execution, even when data is null. A newer, still-evolving GraphQL over HTTP specification defines a separate response media type, application/graphql-response+json, and says clients should treat a body of that type as a GraphQL response whatever the status code, with 4xx or 5xx statuses for requests that fail before execution. A safe default is therefore to read the body of every response, not the status alone, and to check what your server and clients implement.
The same propagation as a runnable program. It uses a small hand-written executor, not a GraphQL library, with a resolver that turns a downstream timeout into a field error, and it prints the three bodies and their byte counts, so the Content-Length values above can be checked:
import json
class FieldError(Exception):
"""A resolver failure that becomes an entry in the response's errors list."""
def __init__(self, message, code):
super().__init__(message)
self.code = code
class NullEscapes(Exception):
"""A non-null field failed, so its parent must become null instead."""
def with_timeout(call, service, limit_ms, code):
"""Run a downstream call; a timeout becomes a field error with a stable code."""
try:
return call()
except TimeoutError:
raise FieldError(f"{service} service timed out after {limit_ms} ms", code)
def slow_shipping_call():
raise TimeoutError() # stands in for an HTTP client whose 800 ms deadline expired
def shipping_resolver():
return with_timeout(slow_shipping_call, "Shipping", 800, "UPSTREAM_TIMEOUT")
ORDER_CHILDREN = [
("id", lambda: "7"),
("status", lambda: "PAID"),
("shipment", shipping_resolver),
("customer", lambda: {"name": "Ava"}),
]
def execute(non_null):
"""Run order { id status shipment customer }; non_null is the set of paths declared with !."""
errors = []
def complete(path, resolver):
failed = False
try:
value = resolver()
except FieldError as exc: # the failure is recorded once, where it happened
errors.append({"message": str(exc), "locations": [{"line": 1, "column": 28}],
"path": path, "extensions": {"code": exc.code}})
value, failed = None, True
except NullEscapes: # a child could not be null: this field becomes null
value, failed = None, True
if failed and ".".join(path) in non_null: # this field cannot hold null either: pass it up
raise NullEscapes()
return value
def order():
return {name: complete(["order", name], fn) for name, fn in ORDER_CHILDREN}
try:
data = {"order": complete(["order"], order)}
except NullEscapes:
data = None # nothing nullable is left above: the whole data is null
body = {"data": data}
if errors:
body["errors"] = errors
return json.dumps(body, separators=(",", ":"))
cases = {
"A shipment nullable": {"order.id", "order.status"},
"B shipment non-null": {"order.id", "order.status", "order.shipment"},
"C shipment and order non-null": {"order.id", "order.status", "order.shipment", "order"},
}
for label, non_null in cases.items():
text = execute(non_null)
print(label, "| bytes:", len(text.encode()))
print(text)
Output:
A shipment nullable | bytes: 258
{"data":{"order":{"id":"7","status":"PAID","shipment":null,"customer":{"name":"Ava"}}},"errors":[{"message":"Shipping service timed out after 800 ms","locations":[{"line":1,"column":28}],"path":["order","shipment"],"extensions":{"code":"UPSTREAM_TIMEOUT"}}]}
B shipment non-null | bytes: 194
{"data":{"order":null},"errors":[{"message":"Shipping service timed out after 800 ms","locations":[{"line":1,"column":28}],"path":["order","shipment"],"extensions":{"code":"UPSTREAM_TIMEOUT"}}]}
C shipment and order non-null | bytes: 184
{"data":null,"errors":[{"message":"Shipping service timed out after 800 ms","locations":[{"line":1,"column":28}],"path":["order","shipment"],"extensions":{"code":"UPSTREAM_TIMEOUT"}}]}
Reading the program: with_timeout is the pattern for every resolver that calls a REST service, a timeout becomes a FieldError with a stable code. complete records that error once, at the field that failed, and then asks whether that field is allowed to be null; if it is not (its path is in non_null), it raises NullEscapes, which the parent's complete catches and applies the same test. The three runs differ only in the non_null set, which is exactly the difference between Cases A, B and C.
Lists. Take items: [Item]! on an order with 50 items where the lookups for 3 items fail. The client gets 47 items and 3 null entries, with 3 errors whose paths end in a list index, such as ["order","items",5]. With items: [Item!]! a single failed item makes the whole list invalid, so the null moves up to order: 50−3=47 good items are lost to protect a guarantee ("no nulls in the list"). Choose per field which guarantee is worth more.
How I would design the resolvers for this layer
- Nullability follows failure independence. Fields served by a separate backend that can fail on its own (
shipment,customer) are nullable. Fields from the same source as their parent (id,status) are non-null. This decides how much of the response survives. - Per-call timeouts inside an overall budget. Give each downstream REST call its own timeout (800 ms in the scenario) smaller than the budget for the whole request (say 2,000 ms, assumed). A resolver that waits indefinitely makes the whole response wait. Turn the timeout into a field-level error with a stable
extensions.code. - Batch per request. If a REST service has a bulk endpoint (for example
GET /customers?ids=3,7,9), put it behind a per-request DataLoader so 20 orders trigger one customers call, not 20. If it has none, the loader can still deduplicate repeated ids and run the remaining single calls in parallel with a concurrency cap (a limit on how many calls may be in flight at once), so a long list cannot open hundreds of connections at once. A batch function can return an error object for one key, so one bad id fails one field rather than the whole batch; if the whole bulk call fails, every key in that batch gets the error. - Cache in two layers. Within a request, the DataLoader cache means the same customer is fetched once even if ten orders share it. Across requests, a time-limited cache keyed by the downstream URL that honours the backend's
Cache-Controlheader is appropriate for slow-changing data;stale-if-error(RFC 5861, aCache-Controlextension) lets a cache serve an expired copy for a stated number of seconds while the backend is failing. Do not cache per-user data in a shared cache without the user in the key. - Protect the backend. Circuit breaking (stop calling a failing service for a short period and fail fast) and retries only for idempotent calls (calls where repeating the request has the same effect as making it once, such as a read or a PUT, unlike a POST that creates an order) and only while budget remains: with an 800 ms timeout and a 2,000 ms budget, after the 120 ms orders call one retry would end at 120+800+800=1720 ms, so a second retry cannot fit.
- Do not leak internals. Return a clean message and a code; keep stack traces, internal host names and raw upstream bodies in server logs, tied to the request id.
A timeline for one customer record, with the assumed headers Cache-Control: max-age=60, stale-if-error=300 on the customers service's response (illustrative):
| Time (s) | Event | Result |
|---|---|---|
| 0 | first read, nothing cached | cache miss: call the service, store the copy |
| 30 | second read | cache hit: copy is 30 s old, within max-age=60, no call |
| 70 | third read, copy is 70 s old (stale) | revalidate: service answers 503, but the copy is only 10 s past its freshness, inside the 300 s stale-if-error allowance, so the stale copy is served |
| 400 | fourth read, service still down | copy is 340 s past freshness, beyond 300 s, so the failure surfaces as a field error |
Operating it
- The status code will not tell you a field failed. Count errors by
extensions.codeand by field path, and alert on the rate, not on non-200 responses alone. - Log the request id and the downstream service per error so one trace shows which backend failed.
- Clients must read
errorseven on a success status, decide per field whether a null is acceptable (hide a shipping widget) or fatal (no order at all), and avoid retrying the whole query for a partial failure unless the failed field matters.
Common mistakes
- Marking everything non-null for neat client types, so one slow backend blanks the whole page.
- Returning HTTP 500 for partial failures, which makes clients and caches throw away the good data.
- Letting a resolver throw raw backend errors into the response.
- Batching only the first level of downstream calls, leaving a per-row call one level deeper.
Unlock Full Question Bank
Get access to all 6 GraphQL and Flexible Query APIs interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.