Backend-for-Frontend and Client-Specific API Design Questions
Shaping API responses to the needs of specific client types: the Backend-for-Frontend (BFF) pattern, one BFF per client versus a shared gateway, client-side composition or a generic API, what belongs in a BFF (including normalizing inconsistent downstream pagination and error formats for one client), and aggregating several backend calls into one client-shaped response. Covers payload shaping (sparse fieldsets and field selection against relational and document stores, partial responses, optional expansion of related collections, delta responses with deletions, compact serialization including binary wire formats), round-trip reduction and composite views for feeds and dashboards, adapting to mobile versus web bandwidth, battery and device constraints (device-appropriate image variants, prefetching and refresh frequency tuned to connection quality), and choosing GraphQL versus REST to fix over- and under-fetching, including incremental migration from REST to GraphQL. Authentication, general REST resource design, versioning, rate limiting, offline sync and real-time transport are covered elsewhere.
What are over-fetching and under-fetching in client-server APIs, and how do REST and GraphQL each deal with them? Describe what a frontend or mobile client feels from each approach.
Sample Answer
Direct answer
Over-fetching means the response carries more data than the screen uses. Under-fetching means one response is not enough, so the client must make follow-up requests to assemble a screen. Both waste the client's time, data allowance and battery. REST fixes them by shaping resources and endpoints on the server: sparse fieldsets (a fields= parameter that lists the only fields the client wants, shown below), embedded related data, or screen-specific endpoints. GraphQL, a query language where the server publishes a schema (a typed list of every object and field a client may ask for), fixes them by letting the client name exactly the fields it wants in a single request, at the price of a heavier server and a harder caching story.
What each problem looks like
Take a feed screen. Each row shows a post title, the author's name and a thumbnail.
- Over-fetching.
GET /postsreturns the whole post: body text, tags, view counts, edit history. The row uses three fields. If each post is 2,000 bytes and a row needs about 100, a page of 20 rows downloads 20 x 2,000 = 40,000 bytes to render 20 x 100 = 2,000 bytes of content, a factor of 20. The phone also parses all of it as JSON (JavaScript Object Notation) and holds it in memory. - Under-fetching.
GET /postsreturnsauthorIdbut not the name. If the 20 posts have 3 distinct authors, the client makes 1 + 3 = 4 requests (the pattern is called N+1: one request for the list, then one more per distinct related item). The author lookups cannot start until the list has arrived, so the screen waits for at least two sequential network round trips (list, then authors), and each extra hop on a weak cellular link is a chance to stall.
How REST deals with it
REST (resources addressed by URL, standard HTTP verbs) has no built-in query language, so you shape responses with conventions:
- Sparse fieldsets:
GET /posts?fields=id,title,author.name,thumbnailUrl. - Embedding or inclusion:
GET /posts?embed=authororinclude=author, so related data rides along (JSON:API, a public REST convention, definesfields[TYPE]andincludeand requires400 Bad Requestwhen a server does not supportinclude). - Screen-shaped endpoints:
GET /screens/feed, which belongs to a Backend-for-Frontend (BFF, a server layer owned by the client team that returns exactly what one client needs).
How GraphQL deals with it
GraphQL exposes one typed schema. The client sends a query that names fields, and the response mirrors its shape:
{ posts(first: 20) { id title author { name } thumbnailUrl(width: 96) } }
Over-fetching disappears because only named fields come back. Under-fetching disappears because the nested author { name } is resolved on the server in the same request (a resolver is the server function that produces the value of one field, here the author's name). Per the GraphQL over HTTP documentation, servers must accept POST for queries and mutations (mutations are the GraphQL operations that write data) and may accept GET for queries only. A response can hold both data and errors, and a response with non-null data should still use a 2xx status, because HTTP has no status for partial success.
What the client feels
| Concern | REST with fieldsets / BFF | GraphQL |
|---|---|---|
| Bytes per screen | Small if the server implements shaping; fixed endpoints over-fetch for other screens | Small by construction, per query |
| Round trips | 1 with embeds or a screen endpoint, otherwise 1 + N (one list request plus one per related item) | 1 per screen query |
| Client CPU | Parses a small JSON; no query building | Parses a small JSON; a client library may normalize results into a cache (split each response into one record per object, keyed by id, so an author shared by many posts is stored once), and that splitting and merging costs CPU on low-end devices |
| CDN (content delivery network) caching | Easy: URL is the cache key, GET is cacheable | Hard with POST; possible with GET plus persisted query ids (short identifiers that replace long query text, which also avoids URL length limits) |
| Developer velocity | Frontend waits for a new field or endpoint if the shape is missing | Frontend adds a field to its own query, no backend ticket, if the schema already exposes it |
| Versioning | New fields are additive; breaking shapes need /v2 or negotiation | Add fields freely and mark old ones with the built-in @deprecated directive (an annotation on a schema field that tells tools and developers the field is going away); usage is visible per field |
| Error handling | HTTP status per request tells the story | Often HTTP 200 with an errors array and partial data, so clients must inspect the body |
Which screens feel it most
- Personalized feed: many small rows, several related entities per row (author, counts, reaction). Under-fetching dominates, so one composed request (GraphQL query or BFF endpoint) matters most.
- Settings screen: one small object, rarely changing. Plain REST is fine and caches well; GraphQL adds little.
- Analytics sync: the client uploads or downloads bulk data in the background. The cost is bytes and radio wake-ups (every time the phone's cellular radio leaves idle to send a request it draws extra battery, so many small requests cost more energy than one batched request), not flexible field choice. Batch it into one request and compress it; a query language is not the lever.
Pitfalls
- GraphQL does not remove over-fetching on the server: a resolver (the function that produces one field) may still load the whole database row. Field selection saves wire bytes, not necessarily database work.
- A permissive
fields=parameter can leak internal columns. Validate it against an allowlist. - Choosing GraphQL to fix under-fetching, then discovering that each nested field issues its own database query (the N+1 problem), swaps a client problem for a server one.
A mobile detail screen always needs an object but only sometimes needs its large related collection, such as comments. How would you design a single endpoint so the client can get the object with or without the collection? Show a sample request and response and explain the trade-offs.
Sample Answer
Direct answer
Add an opt-in include query parameter to the detail endpoint. GET /v1/articles/7 returns the object plus a cheap commentCount. GET /v1/articles/7?include=comments&comments_limit=20 returns the same object plus a bounded first page of comments under an included key, with a link to fetch more. The collection is never embedded by default, never unbounded, and an unsupported include value is rejected with 400, not ignored.
Sample requests and responses
Run in a Node 22 container with no dependencies (docker run --rm -v "$PWD":/w -w /w node:22 node include.mjs), include.mjs:
// Run: node include.mjs (Node 22, no dependencies)
import http from 'node:http';
const article = { id: 7, title: 'Article 7', body: 'Lorem ipsum '.repeat(150) };
const comments = Array.from({ length: 12 }, (_, k) => ({ id: 700 + k, author: ['Ana', 'Ben', 'Chen'][k % 3], text: 'Nice post '.repeat(5).trim() }));
const SUPPORTED = new Set(['comments']);
const server = http.createServer((req, res) => {
const u = new URL(req.url, 'http://x');
const send = (s, o) => { res.writeHead(s, { 'content-type': 'application/json' }); res.end(JSON.stringify(o)); };
if (u.pathname !== '/v1/articles/7') return send(404, {});
const include = (u.searchParams.get('include') || '').split(',').filter(Boolean);
const unknown = include.filter(i => !SUPPORTED.has(i));
if (unknown.length) return send(400, { error: 'unsupported_include', values: unknown }); // reject, never ignore silently
const out = { data: { ...article, commentCount: comments.length } }; // count is always present and cheap
if (include.includes('comments')) {
const raw = u.searchParams.get('comments_limit');
const asked = raw === null ? 20 : Number(raw);
if (!Number.isInteger(asked) || asked < 1) return send(400, { error: 'invalid_comments_limit' }); // 0, -1, 'abc', 2.5 are rejected
const limit = Math.min(asked, 50); // server-side cap on the collection
const items = comments.slice(0, limit);
out.included = { comments: { items, next: items.length < comments.length ? `/v1/articles/7/comments?after=${items.at(-1).id}` : null } };
}
send(200, out);
});
await new Promise(r => server.listen(0, r));
const base = `http://127.0.0.1:${server.address().port}`;
for (const q of ['', '?include=comments&comments_limit=2', '?include=likes', '?include=comments&comments_limit=-1']) {
const r = await fetch(base + '/v1/articles/7' + q); const t = await r.text();
console.log(`GET /v1/articles/7${q}\n -> ${r.status}, ${Buffer.byteLength(t)} bytes`);
console.log(' ' + t.replace(/"body":"[^"]*"/, '"body":"..."'));
}
server.close();
Output (the long body is elided by the script's print step):
GET /v1/articles/7
-> 200, 1865 bytes
{"data":{"id":7,"title":"Article 7","body":"...","commentCount":12}}
GET /v1/articles/7?include=comments&comments_limit=2
-> 200, 2114 bytes
{"data":{"id":7,"title":"Article 7","body":"...","commentCount":12},"included":{"comments":{"items":[{"id":700,"author":"Ana","text":"Nice post Nice post Nice post Nice post Nice post"},{"id":701,"author":"Ben","text":"Nice post Nice post Nice post Nice post Nice post"}],"next":"/v1/articles/7/comments?after=701"}}}
GET /v1/articles/7?include=likes
-> 400, 50 bytes
{"error":"unsupported_include","values":["likes"]}
GET /v1/articles/7?include=comments&comments_limit=-1
-> 400, 34 bytes
{"error":"invalid_comments_limit"}
With the 12-comment data set the cap of 50 cannot be seen. Changing length: 12 to length: 60000 and requesting comments_limit=500 returns a page of 50 comments, while comments_limit=-1, 0 and abc all return the same 400. Without the integer check, -1 would reach slice(0, -1) and return every comment but the last.
Design choices
- Opt-in, default off. The screen that does not need comments pays nothing.
commentCountis always returned, so the screen can show "12 comments" and a button without loading any. - Bounded by the server.
comments_limitmust be a whole number of at least 1 (anything else is a400) and is capped on the server (50 here) whatever the client asks. An "include everything" request on an article with 50,000 comments would otherwise become the new over-fetch.nextis a link to the rest of the list as its own endpoint (a sub-resource). Itsafter=701part is a cursor: a bookmark that says "continue after the item with id 701", which is the last comment already delivered. The app requests that URL when the user scrolls, and the server answers with the next comments after 701, so nothing is repeated or skipped even if new comments arrive meanwhile. - A separate
includedsection, not nesting insidedata. The primary object keeps one stable shape with or without the include. A compound document is one response that carries the main resource plus related resources in a separate section; for example the article indataand its comments inincluded, rather than comments mixed into the article's own fields. This mirrors the compound-document idea in JSON:API, a public REST convention whose specification also says a server that does not supportincludemust answer400 Bad Request, and that it must not return resources nobody requested. - Strict validation.
include=likesreturns400with the offending value. Silently ignoring it would let a typo ship and the screen would just show no likes.
Trade-offs
| Option | Round trips | Bytes when comments are not needed | Cache behaviour |
|---|---|---|---|
| Always embed comments | 1 | Large (always paid) | One URL per article |
| Two endpoints (article, then comments) | 2 when needed, 1 otherwise | Minimal | Each URL cached on its own; comments can have a shorter lifetime than the article |
Opt-in include (this design) | 1 either way | Minimal | One cache entry per include combination |
In the run above, the plain request is 1,865 bytes and the request with two embedded comments is 2,114 bytes. The 249-byte difference is the two comments plus their wrapper, and it grows with the limit.
- Cache-key growth. Each distinct
includeandcomments_limitvalue is a separate URL for a CDN (content delivery network) or HTTP cache. Offer a few fixed combinations (limit 20 only) so the hit rate stays high. - Different change rates. If the article changes weekly and comments change by the minute, embedding ties their freshness together: the cached composite is only as fresh as its most volatile part. When comments are very volatile, prefer the two-endpoint option.
- Latency. With
include, the server waits for the slowest of the two data sources before sending anything. If comments come from a slow service, make the client fetch them separately, so the article paints first. - GraphQL alternative. A query can ask for
article { title comments(first: 20) { text } }or leavecommentsout, which solves the same problem without a parameter convention, with the caching trade-offs of aPOSTendpoint.
Pitfalls
- Letting
includeaccept arbitrary nested paths (comments.author.friends), which turns a detail endpoint into a graph traversal. Support a short fixed list. - Returning
included.comments: []when the user is not authorized to see comments. Check authorization for included data the same way as for the primary resource. For example, if comments on a members-only article are visible only to subscribers, a non-subscriber requesting?include=commentsshould get403, or noincludedsection with a clear reason, not an empty list that looks like "no comments yet". - Forgetting the count: without
commentCountthe client has to load the collection to know whether one exists.
The responses of a JSON API consumed by mobile devices are too heavy for cellular connections. Name three changes you would make to cut the bytes on the wire, and for each one explain how you would implement it on the server and how the client benefits.
Sample Answer
Direct answer
Three changes, in the order I would ship them:
- Negotiate HTTP compression (gzip, and Brotli where the client supports it).
- Trim the payload to what the screen reads: send only needed fields, omit nulls and unused columns, shorten values.
- Add conditional requests (ETag plus
If-None-Match) so an unchanged response costs a headers-only304 Not Modified.
The run below puts numbers on each, on a 50-row order list.
Runnable demonstration
In a Node 22 container with no dependencies: docker run --rm -v "$PWD":/w -w /w node:22 node shrink.mjs. shrink.mjs:
// Run: node shrink.mjs (Node 22, no dependencies)
import http from 'node:http';
import zlib from 'node:zlib';
import crypto from 'node:crypto';
// 50 order rows as the backend stores them: many nullable columns, verbose names, fields this screen never reads.
const orders = Array.from({ length: 50 }, (_, i) => ({
order_identifier: `ord_${100000 + i}`, customer_display_name: `Customer ${i % 7}`, order_status: ['shipped', 'pending', 'delivered'][i % 3],
total_amount_cents: 1999 + i * 37, currency_code: 'USD', placed_at_iso8601: `2026-09-${String((i % 28) + 1).padStart(2, '0')}T10:15:00Z`,
gift_message: null, coupon_code: i % 10 === 0 ? 'FALL10' : null, shipping_notes: null, internal_audit_trail: 'x'.repeat(120), warehouse_pick_sequence: i,
}));
// Change 1: send only what the list screen reads (and omit null values entirely).
const trimmed = orders.map(o => { const r = { id: o.order_identifier, status: o.order_status, total: o.total_amount_cents, placed: o.placed_at_iso8601 }; if (o.coupon_code) r.coupon = o.coupon_code; return r; });
const server = http.createServer((req, res) => {
const u = new URL(req.url, 'http://x');
const body = Buffer.from(JSON.stringify(u.searchParams.get('mode') === 'full' ? orders : trimmed));
const etag = `W/"${crypto.createHash('sha1').update(body).digest('hex').slice(0, 12)}"`; // weak ETag: same content, any encoding
const headers = { 'content-type': 'application/json', vary: 'Accept-Encoding', etag };
const strip = t => t.trim().replace(/^W\//, ''); // weak comparison: ignore the W/ prefix
const offered = (req.headers['if-none-match'] || '').split(',').map(strip); // the header may carry several tags
if (offered.includes(strip(etag))) { res.writeHead(304, headers); return res.end(); } // Change 3: nothing changed, send no body
const ae = req.headers['accept-encoding'] || '';
if (/\bbr\b/.test(ae)) { headers['content-encoding'] = 'br'; res.writeHead(200, headers); return res.end(zlib.brotliCompressSync(body)); } // Change 2: compression
if (/\bgzip\b/.test(ae)) { headers['content-encoding'] = 'gzip'; res.writeHead(200, headers); return res.end(zlib.gzipSync(body)); }
res.writeHead(200, headers); res.end(body);
});
await new Promise(r => server.listen(0, r));
const port = server.address().port;
// node:http does not decompress, so the byte count is what crossed the wire.
const request = (path, headers = {}) => new Promise(resolve => http.get({ port, path, headers }, res => {
let n = 0; res.on('data', c => (n += c.length)); res.on('end', () => resolve({ status: res.statusCode, bytes: n, etag: res.headers.etag }));
}));
const show = (label, r) => console.log(label.padEnd(44), String(r.status).padStart(3), String(r.bytes).padStart(7), 'body bytes');
show('all columns, no compression', await request('/orders?mode=full', { 'accept-encoding': 'identity' }));
show('all columns + gzip', await request('/orders?mode=full', { 'accept-encoding': 'gzip' }));
show('trimmed fields, no compression', await request('/orders', { 'accept-encoding': 'identity' }));
show('trimmed + gzip', await request('/orders', { 'accept-encoding': 'gzip' }));
const brotli = await request('/orders', { 'accept-encoding': 'br, gzip' });
show('trimmed + Brotli (client offers br, gzip)', brotli);
show('revalidate with If-None-Match, unchanged', await request('/orders', { 'accept-encoding': 'br, gzip', 'if-none-match': brotli.etag }));
server.close();
Output:
all columns, no compression 200 21193 body bytes
all columns + gzip 200 1126 body bytes
trimmed fields, no compression 200 4323 body bytes
trimmed + gzip 200 581 body bytes
trimmed + Brotli (client offers br, gzip) 200 394 body bytes
revalidate with If-None-Match, unchanged 304 0 body bytes
Reductions against the 21,193-byte starting point: trimming alone 79.6% (4,323 bytes); gzip alone 94.7% (1,126); trimming plus gzip 97.3% (581); trimming plus Brotli 98.1% (394); an unchanged revalidation sends no body at all. Trimming still halves what gzip leaves: 581 versus 1,126 bytes is 48.4% less. The sample rows are repetitive, so compression looks extra strong here; real data compresses less, which is a reason not to rely on compression alone.
Tracing one request through the script
Take the fifth request, GET /orders with Accept-Encoding: br, gzip and no If-None-Match:
- The server serializes the trimmed rows to JSON bytes and hashes those uncompressed bytes into the ETag, for example
W/"3f2a9c01b7de". req.headers['if-none-match']isundefined, so the list of offered tags is empty and the 304 branch is skipped.- The test
/\bbr\b/looks forbras a whole word in the header value.br, gzipmatches, so the server setscontent-encoding: br, compresses with Brotli and sends 394 bytes. A client that offers onlygzipfails that test (no whole wordbr) and passes the next one,/\bgzip\b/; a client that offersidentityor nothing fails both and gets the plain 4,323 bytes. - Every response carries
Vary: Accept-Encodingand the sameETag.
The sixth request is identical except that it adds If-None-Match with the ETag the fifth response returned. The hash is of the uncompressed content, so it is equal; the server answers 304 with the same headers and no body before any compression happens.
Change 1: compression
- Server: read the request's
Accept-Encodingheader (the client's list of encodings it can decode, for examplebr, gzip), pick one, compress the body and answer withContent-Encoding: brorgzip. Most web servers and gateways do this with a setting; the script does it by hand. Always addVary: Accept-Encoding.Varylists the request headers that influenced the response; MDN describes it as making caches store responses separately per value of those headers. So a shared cache (one serving many users, such as a CDN) keeps the Brotli, gzip and plain versions of/ordersas separate entries and hands each client the one it can decode. Without it, the cache could replay the first client's Brotli bytes to a client that cannot read them. - Client benefit: fewer bytes cross the radio, so the screen fills sooner on a slow link and the radio is active for less time.
- Cost: the server spends CPU compressing and the client spends a little CPU decompressing. MDN recommends compressing everything except already-compressed files such as images, audio and video, because compressing them again is often counterproductive. Higher compression levels cost more server CPU, so cache the compressed body or precompress static content instead of recompressing per request.
- Compatibility: negotiation handles old clients for free: one that sends no
Accept-Encodinggets plain JSON. Check that your mobile HTTP library actually sends the header and decodes the reply.
Change 2: trim the payload
- Server: return a purpose-built shape: an explicit
fieldsparameter or a screen-specific DTO (data transfer object, a class that holds only the fields one response needs), omitnulland default values, drop internal columns (internal_audit_trail), and use shorter names or values where a field is repeated 50 times. The script keeps four fields pluscouponwhen present. - Client benefit: smaller payload to download and parse, less memory.
- Cost and compatibility: the trimmed shape renamed
order_identifiertoid. That is a breaking change (one that makes existing, unmodified clients fail or misread the data): an older app that readsorder_identifierwould find it missing. Ship the new shape behind a new endpoint, a version header or an opt-in parameter, and keep serving the old shape until old app versions are gone. Omittingnullis also a contract change: a client that testsfield === nullmust learn that "missing" means the same thing.
Change 3: conditional requests
- Server: compute a validator (a value that identifies the current version of the response; an ETag is a fingerprint of the content) and return it in the
ETagheader. A strong ETag ("abc") promises the bytes are identical; a weak ETag (W/"abc") promises only that the content is equivalent, which MDN notes may differ byte for byte, such as the same data in different encodings. When a later request carriesIf-None-Matchwith that value, answer304 Not Modifiedwith no body. Per MDN, the304repeats headers such asETagandVary, andIf-None-Matchuses weak comparison and may carry several tags, so the script drops anyW/prefix and answers304if any offered tag equals its own. The tag is the same for every encoding because it is a hash of the uncompressed bytes, not because of theW/prefix. - Client benefit: pull-to-refresh and screen revisits on unchanged data cost a headers-only exchange. The last row of the output shows
304with 0 body bytes. - Cost: the server still computes or looks up the validator; the saving is bytes, not backend work, unless the validator is cheap (a version number or an
updated_atvalue, not a hash of the full body).
CPU versus bandwidth, summarized
| Change | Bytes saved | Server CPU | Client CPU |
|---|---|---|---|
| Compression | High on text | Compress each response (or cache it) | Small decompress cost |
| Trimming | Medium to high | Lower (less to serialize) | Lower (less to parse) |
| Conditional requests | The whole body when unchanged | Validator check | None |
Trimming reduces work on both ends, conditional requests remove whole responses when nothing changed, and compression trades CPU for bytes.
Pitfalls
- Trimming and renaming fields in place, which breaks older clients.
- Forgetting
Vary: Accept-Encodingso a cache serves gzip to a client that cannot read it. - Using a strong content hash as the validator on a huge response: you still pay to build it.
A social app's home feed mixes posts, ads and friend suggestions, and the mobile client currently makes many calls to render it. Design server-side strategies that minimize the number of calls the client needs. Consider personalization, A/B tests and privacy filters, and show the API shape and caching approach.
Sample Answer
Direct answer
Give the mobile app one screen endpoint, GET /v1/home?cursor=&limit=, that returns an ordered list of lightweight references plus a table of the entities they point to. The server (a BFF, meaning a backend built for one client's screens) asks the ranking service (an internal service that decides which posts, ads and suggestions this viewer sees and in what order, and returns only ids) for the order, removes anything the viewer must not see before paging, assigns the A/B arm, hydrates each distinct entity once (hydrating means looking up the full record, such as the post text or the author's name, for an id; doing it once per distinct id means an author with five posts is fetched once), and returns everything in one response. Cache the shared pieces (post bodies, ad creatives, media) on the server and in a CDN (content delivery network); treat the per-user ordering as private.
API shape
GET /v1/home?limit=20 HTTP/1.1
Authorization: Bearer <token>
If-None-Match: "feed-4f19"
{
"experiment": { "compact-cards": "control" },
"items": [
{ "type": "post", "id": "p1" },
{ "type": "post", "id": "p2" },
{ "type": "ad", "id": "ad0" },
{ "type": "suggestion", "id": "sg1" }
],
"entities": {
"posts": { "p1": { "id": "p1", "authorId": "u4", "text": "...", "likes": 312 } },
"ads": { "ad0": { "id": "ad0", "headline": "Ad 0", "image": "https://cdn.example/ad/0.jpg" } },
"suggestions": { "sg1": { "id": "sg1", "userId": "u1", "mutual": 1 } },
"users": { "u4": { "id": "u4", "name": "User 4", "avatar": "https://cdn.example/a/u4.jpg" } }
},
"nextCursor": "20"
}
items carries the order and the type; entities carries the content keyed by id. A client store (a normalized cache, meaning one record per id that every screen reads) updates a like count in one place and every card showing that post reflects it.
Why it cuts calls
Calls are counted from code, not estimated. The model below builds a seeded 20-item page (16 posts, 2 ads, 2 suggestions) and counts what a client would need if it assembled the screen itself.
| Strategy | Calls for page 1 | Dependency depth |
|---|---|---|
| Client fetches ranking, then each item, then each user | 30 (1 ranking + 20 items + 9 users) | 3 |
| Client batches hydration per type | 5 (ranking, posts, ads, suggestions, users) | 3 |
| Screen endpoint | 1 | 1 |
Dependency depth is the number of calls that must finish before the next can start: the client cannot ask for an item until the ranking names it, and cannot ask for a user until the item names the author, so ranking, items and users form three levels (depth 3). The screen endpoint does all three levels on the server, next to the data, so the client sees depth 1. Depth matters as much as count on a weak connection, because each level costs a full round trip.
Personalization, A/B tests and privacy filters
- Personalization stays in the ranking service. The BFF receives references in order and never scores anything, so the model can change without a client release.
- A/B tests: assign the arm (the variant group, such as
controlorcompact, that a user is placed in for an experiment) on the server from a stable hash of the user id and experiment name, and echo it inexperimentso the client can log which arm was shown. A hash function turns the same input into the same number every time, so the assignment is identical on every request without storing it. ForbucketOfin the model below: SHA-256 of the textviewer-1:compact-cardsgives 32 bytes;readUInt32BE(0)reads the first four bytes (hexbd800f0e) as the unsigned number 3,179,286,286; that number modulo the number of arms (2) is 0, and arm 0 iscontrol. Another user id hashes to a different number and so lands in either arm, which spreads users across the arms roughly evenly. To keep the shared cache effective, vary layout by arm on the client, using the same entities; do not generate different server fragments per arm unless the content itself differs. - Privacy filters run on the server, before the page is cut. Blocked and muted authors never reach the response or the entity table, and filtering first keeps page sizes and cursors consistent. In the model below the ranking service returns 45 references (40 posts, 3 ads, 2 suggestions); the filter removes 9, leaving 36 visible. Page 1 takes 20, so page 2 holds the remaining 36 - 20 = 16, and the cursor
"20"points at the right place. Paging first and filtering afterwards would instead leave pages with a varying number of cards. Filtering on the client would already have shipped the data, and would also make pages that contain 20 refs show fewer cards (for example 17 if three belong to blocked authors).
Caching approach
| Layer | What | Rule |
|---|---|---|
| Server fragment cache | Post bodies, ad creatives, user cards, keyed by id and version | Viewer-independent, so shared across users; invalidate on edit. |
| Visibility decision | Blocked / muted / audience checks | Recomputed per request from small per-user sets; never cached in a shared fragment. |
| Ranking session | The ordered refs for this viewer | Cached for a few minutes per user so page 2 continues the same list instead of re-ranking and shifting items. The cursor carries the session id and position. |
| HTTP response | Cache-Control: private plus an ETag | private means only the user's own device may store it; MDN warns that a personalized response without private can be stored in a shared cache and reused for other users. Pull-to-refresh sends If-None-Match and gets 304 Not Modified when the ranking has not changed. |
| Media | Images and video | Long-lived, immutable URLs on the CDN. |
Runnable model
Seeded data, a ranking stand-in that returns references, the privacy filter, a stable arm assignment and the counters above. Run in a node:22 container (Node 22.23.3) with node feed.mjs; there is nothing to install.
import { createHash } from 'node:crypto';
// ---- deterministic data (seeded generator) ----
let seed = 42;
const rnd = () => (seed = (seed * 1664525 + 1013904223) >>> 0) / 2 ** 32;
const pick = (a) => a[Math.floor(rnd() * a.length)];
const authors = Object.fromEntries(Array.from({ length: 12 }, (_, i) => [`u${i}`, { id: `u${i}`, name: `User ${i}`, avatar: `https://cdn.example/a/u${i}.jpg` }]));
const posts = Object.fromEntries(Array.from({ length: 60 }, (_, i) => [`p${i}`, { id: `p${i}`, authorId: pick(Object.keys(authors)), text: 'Post body '.repeat(8) + i, likes: Math.floor(rnd() * 500) }]));
const ads = Object.fromEntries(Array.from({ length: 6 }, (_, i) => [`ad${i}`, { id: `ad${i}`, headline: `Ad ${i}`, image: `https://cdn.example/ad/${i}.jpg`, advertiser: `Brand ${i}` }]));
const suggestions = Object.fromEntries(Array.from({ length: 8 }, (_, i) => [`sg${i}`, { id: `sg${i}`, userId: `u${i}`, mutual: i }]));
// ---- per-request inputs ----
const viewer = { id: 'viewer-1', blocked: new Set(['u3', 'u7']), muted: new Set(['u5']) };
const bucketOf = (userId, experiment, arms) =>
arms[createHash('sha256').update(userId + ':' + experiment).digest().readUInt32BE(0) % arms.length];
// ---- the ranking service output: ordered refs only, no bodies ----
function rankedRefs() {
const refs = [];
for (let i = 0; i < 40; i++) refs.push({ type: 'post', id: `p${i}` });
[4, 12, 24].forEach((at, k) => refs.splice(at, 0, { type: 'ad', id: `ad${k}` }));
refs.splice(8, 0, { type: 'suggestion', id: "sg1" }, { type: "suggestion", id: "sg2" });
return refs;
}
// ---- the BFF: filter, hydrate once, dedupe into an entity table ----
function homeFeed({ cursor = 0, limit = 20 }) {
const arm = bucketOf(viewer.id, 'compact-cards', ['control', 'compact']);
const visible = rankedRefs().filter((r) => {
if (r.type === 'post') { const a = posts[r.id].authorId; return !viewer.blocked.has(a) && !viewer.muted.has(a); }
if (r.type === 'suggestion') return !viewer.blocked.has(suggestions[r.id].userId);
return true;
});
const page = visible.slice(cursor, cursor + limit);
const entities = { posts: {}, ads: {}, suggestions: {}, users: {} };
for (const r of page) {
if (r.type === 'post') { const p = posts[r.id]; entities.posts[r.id] = p; entities.users[p.authorId] = authors[p.authorId]; }
if (r.type === 'ad') entities.ads[r.id] = ads[r.id];
if (r.type === 'suggestion') { const s = suggestions[r.id]; entities.suggestions[r.id] = s; entities.users[s.userId] = authors[s.userId]; }
}
return { removedByPrivacy: rankedRefs().length - visible.length, experiment: { 'compact-cards': arm }, items: page, entities, nextCursor: cursor + limit < visible.length ? String(cursor + limit) : null };
}
const page1 = homeFeed({});
const bytes = (o) => Buffer.byteLength(JSON.stringify(o));
// Same screen with the "N+1" pattern a client would build itself: embed full author inside every post
const embedded = page1.items.map((r) => {
if (r.type === 'post') return { ...posts[r.id], author: authors[posts[r.id].authorId] };
if (r.type === 'ad') return ads[r.id];
const s = suggestions[r.id]; return { ...s, user: authors[s.userId] };
});
// Round trips if the client composes the screen itself
const idsCall = 1;
const perItem = page1.items.length;
const uniqueAuthors = Object.keys(page1.entities.users).length;
console.log('items on page 1:', page1.items.length, '| types:', JSON.stringify(page1.items.reduce((m, r) => (m[r.type] = (m[r.type] ?? 0) + 1, m), {})));
console.log('client-composed calls (1 ranking + 1 per item + 1 per unique user: authors and suggested users):', idsCall + perItem + uniqueAuthors);
console.log('client-composed calls if hydration is batched per type:', idsCall + 3 + 1, "(ranking, then posts + ads + suggestions in parallel, then users): dependency depth 3");
console.log('BFF calls from the client: 1');
console.log("refs removed by the privacy filter before paging:", page1.removedByPrivacy, "| blocked or muted authors still in response:", JSON.stringify(Object.keys(page1.entities.users).filter((u) => viewer.blocked.has(u) || viewer.muted.has(u))));
console.log('bytes, authors embedded in every post:', bytes(embedded));
console.log('bytes, entity table (items + entities):', bytes({ items: page1.items, entities: page1.entities }));
console.log('A/B arm for viewer-1 is stable across calls:', bucketOf('viewer-1', 'compact-cards', ['control', 'compact']) === page1.experiment['compact-cards'], page1.experiment);
const page2 = homeFeed({ cursor: +page1.nextCursor });
const overlap = page2.items.filter((r) => page1.items.some((q) => q.id === r.id));
console.log('page 2 cursor:', page1.nextCursor, '| items:', page2.items.length, '| ids repeated from page 1:', overlap.length);
console.log('sample item refs:', JSON.stringify(page1.items.slice(0, 3)));
It prints:
items on page 1: 20 | types: {"post":16,"ad":2,"suggestion":2}
client-composed calls (1 ranking + 1 per item + 1 per unique user: authors and suggested users): 30
client-composed calls if hydration is batched per type: 5 (ranking, then posts + ads + suggestions in parallel, then users): dependency depth 3
BFF calls from the client: 1
refs removed by the privacy filter before paging: 9 | blocked or muted authors still in response: []
bytes, authors embedded in every post: 3778
bytes, entity table (items + entities): 3769
A/B arm for viewer-1 is stable across calls: true { 'compact-cards': 'control' }
page 2 cursor: 20 | items: 16 | ids repeated from page 1: 0
sample item refs: [{"type":"post","id":"p1"},{"type":"post","id":"p2"},{"type":"ad","id":"ad0"}]
In this model the cursor is the bare offset "20" because its ranking is a fixed list; a production cursor would also carry the ranking session id, as the caching table says. The privacy filter removed 9 references before paging, and none of the blocked or muted authors appears in the response. Page 2 repeats no ids from page 1. The embedded-author and entity-table byte counts are within 0.3% of each other on this page (3,778 against 3,769 bytes), so the entity table is chosen for consistent updates in the client store, not for size.
Trade-offs and pitfalls
- Slow ad or suggestion service. Give each hydration call a deadline and return the feed without that slot rather than waiting; the feed is useful with posts alone.
- Cursor drift. A pure offset cursor ("start at item 20") breaks when the ranking changes between page requests, because items move and the client sees duplicates or skips some; tie the cursor to a ranking session so page 2 continues the list page 1 came from.
- Shared-cache leaks. The failure to avoid is a personalized body or ordering stored under a public key. Keep user-specific data out of any shared cache key.
- Over-fetching in the first page. Return a small first page (for example 10) with
limitset by the client for time to first content, then larger pages. - Impression logging (recording that an ad or post was shown on screen) belongs in a separate fire-and-forget event call (the client sends it and does not wait for or depend on the reply), not in the feed response, so ad measurement does not make the read slower.
Your mobile app's article list downloads full article objects but each row only shows a title, an author name and a thumbnail. How would you let a client ask for just what a screen needs? Show what the request and response could look like for REST and for GraphQL, and say what the server has to be careful about (computed fields, default fields, caching).
Sample Answer
Direct answer
Let the client name the fields. In REST that is a sparse fieldset (a query parameter listing the fields to return): GET /v1/articles?fields=id,title,author.name,thumbnailUrl. In GraphQL it is the selection set of the query (the list of field names written inside the braces, such as {articles{id title}}). In both cases the server must check the request against an allowlist (a fixed list of permitted field names; anything not on it is refused) of public fields, define what it returns when the client names none, compute derived fields on demand, and keep the cache key predictable.
Request and response, REST
GET /v1/articles?fields=id,title,author.name,thumbnailUrl&thumb_w=96
{"data":[{"author":{"name":"Ana Ruiz"},"id":1,"thumbnailUrl":"https://img.example.com/img1_96.jpg","title":"Article 1"}]}
Request and response, GraphQL
POST /graphql
content-type: application/json
{"query":"{articles{id title author{name} thumbnailUrl(width:96)}}"}
{"data":{"articles":[{"id":"1","title":"Article 1","author":{"name":"Ana Ruiz"},"thumbnailUrl":"https://img.example.com/img1_96.jpg"}]}}
A runnable server with both styles
Run it in a Node 22 container (the graphql package installs first):
docker run --rm -v "$PWD":/w -w /w node:22 sh -c 'npm i --no-audit --no-fund graphql@16 && node fields.mjs'
fields.mjs:
// Run: npm i graphql@16 && node fields.mjs (Node 22)
import http from 'node:http';
import { buildSchema, graphql } from 'graphql';
const authors = new Map([[1, 'Ana Ruiz'], [2, 'Ben Okafor'], [3, 'Chen Wei']]);
const articles = Array.from({ length: 20 }, (_, i) => ({
id: i + 1, title: `Article ${i + 1}`, body: 'Lorem ipsum '.repeat(150), authorId: (i % 3) + 1, imageId: `img${i + 1}`,
tags: ['a', 'b', 'c'], publishedAt: `2026-09-${String(i + 1).padStart(2, '0')}T08:00:00Z`, internalNotes: 'staff only',
}));
// Allowlist of public fields. Each one reads from a source column; thumbnailUrl is computed from imageId.
const DEFAULT = ['id', 'title', 'author.name', 'thumbnailUrl']; // used when ?fields= is absent
const compute = {
id: a => a.id, title: a => a.title, body: a => a.body, publishedAt: a => a.publishedAt, tags: a => a.tags,
'author.id': a => a.authorId, 'author.name': a => authors.get(a.authorId),
thumbnailUrl: (a, w) => `https://img.example.com/${a.imageId}_${w}.jpg`,
};
const fail = msg => Object.assign(new Error(msg), { status: 400 });
const WIDTHS = new Set([48, 96, 192]); // the only thumbnail sizes the image cache will hold
const checkWidth = w => { if (!WIDTHS.has(w)) throw fail(`width must be one of ${[...WIDTHS]}`); return w; };
const parseWidth = v => checkWidth(v == null ? 96 : /^\d+$/.test(v) ? Number(v) : NaN);
function parseFields(all) { // all = every value of ?fields=, as an array
if (all.length === 0) return DEFAULT;
if (all.length > 1) throw fail('fields may appear only once');
const list = [...new Set(all[0].split(',').filter(Boolean))].sort(); // sorted and de-duplicated: one response body per field set
if (list.length === 0) throw fail('fields names no field');
const bad = list.filter(f => !Object.hasOwn(compute, f)); // own keys only: 'constructor' and 'toString' are inherited, and must not pass
if (bad.length) throw fail(`unknown fields: ${bad.join(',')}`); // internalNotes is not in the allowlist, so it can never be asked for
return list;
}
function shape(a, fields, w) {
const out = {};
for (const f of fields) { const [p, c] = f.split('.'); c ? ((out[p] ??= {})[c] = compute[f](a, w)) : (out[p] = compute[f](a, w)); }
return out;
}
const schema = buildSchema(`
type Author { name: String! }
type Article { id: ID! title: String! body: String! author: Author! thumbnailUrl(width: Int = 96): String! }
type Query { articles: [Article!]! }`);
const rootValue = { articles: () => articles.map(a => ({ ...a, author: { name: authors.get(a.authorId) }, thumbnailUrl: ({ width }) => compute.thumbnailUrl(a, checkWidth(width)) })) };
const server = http.createServer((req, res) => {
const u = new URL(req.url, 'http://x');
const send = (s, o) => { res.writeHead(s, { 'content-type': 'application/json' }); res.end(JSON.stringify(o)); };
try {
if (u.pathname === '/v1/articles/full') return send(200, { data: articles }); // what the app downloads today
if (u.pathname === '/v1/articles') return send(200, { data: (() => { const f = parseFields(u.searchParams.getAll('fields')), w = parseWidth(u.searchParams.get('thumb_w')); return articles.map(a => shape(a, f, w)); })() });
if (u.pathname === '/graphql') { let b = ''; req.on('data', c => (b += c)); req.on('end', async () => send(200, await graphql({ schema, source: JSON.parse(b).query, rootValue }))); return; }
send(404, {});
} catch (e) { send(e.status || 500, { error: e.message }); }
});
await new Promise(r => server.listen(0, r));
const base = `http://127.0.0.1:${server.address().port}`;
const size = async (path, init) => { const r = await fetch(base + path, init); const t = await r.text(); return { status: r.status, bytes: Buffer.byteLength(t), body: t }; };
const line = (l, b) => console.log(l.padEnd(34), String(b).padStart(6), 'bytes');
const full = await size('/v1/articles/full'); line('REST, full objects', full.bytes);
const dflt = await size('/v1/articles'); line('REST, default field set', dflt.bytes);
const sel = await size('/v1/articles?fields=title,id,thumbnailUrl,author.name'); line('REST, ?fields=... same four', sel.bytes);
console.log('first row:', JSON.stringify(JSON.parse(sel.body).data[0]));
const gq = '{articles{id title author{name} thumbnailUrl(width:96)}}';
const gql = await size('/graphql', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ query: gq }) });
line('GraphQL POST response', gql.bytes);
console.log('GraphQL request body:', Buffer.byteLength(JSON.stringify({ query: gq })), 'bytes;', 'saving vs full:', (100 * (1 - sel.bytes / full.bytes)).toFixed(1) + '%');
const bad = await size('/v1/articles?fields=title,internalNotes'); console.log('internalNotes ->', bad.status, bad.body);
const inherited = await size('/v1/articles?fields=constructor'); console.log('constructor ->', inherited.status, inherited.body);
const wide = await size('/v1/articles?fields=thumbnailUrl&thumb_w=100000'); console.log('thumb_w=100000 ->', wide.status, wide.body);
server.close();
Output:
REST, full objects 39163 bytes
REST, default field set 2277 bytes
REST, ?fields=... same four 2277 bytes
first row: {"author":{"name":"Ana Ruiz"},"id":1,"thumbnailUrl":"https://img.example.com/img1_96.jpg","title":"Article 1"}
GraphQL POST response 2330 bytes
GraphQL request body: 68 bytes; saving vs full: 94.2%
internalNotes -> 400 {"error":"unknown fields: internalNotes"}
constructor -> 400 {"error":"unknown fields: constructor"}
thumb_w=100000 -> 400 {"error":"width must be one of 48,96,192"}
The 20-row list drops from 39,163 bytes (full objects, each with a body) to 2,277 bytes, a 94.2% reduction: 100 x (1 - 2,277 / 39,163). The GraphQL response is 2,330 bytes, 53 more: the {"articles":...} wrapper adds 13 bytes and GraphQL serializes the ID type as a string, so each of the 20 ids gains two quote characters (40 bytes). Its request is a 68-byte body; the REST request is a URL. The list screen needs those four fields only, so both styles cut the same dead weight.
Reading the server code
- Data and allowlist.
articlesholds 20 records; each has fields such asbodyandinternalNotesthat a list screen should not download.computemaps every public field name to a small function that reads the value from a record, so a name missing fromcomputecan never be returned. parseFields(q)turns thefieldsquery string into a clean list. With nofieldsit returnsDEFAULT. Otherwise it splits on commas, drops empty pieces, removes duplicates with aSet, and sorts, sotitle,idandid,titleboth become['id','title']and return the same body. The cache key, which is the URL as sent, is not changed by this. It rejects a repeatedfieldsparameter, an empty list, and any name that is not an own key ofcomputewith a400. The test isObject.hasOwn, notin:inalso finds inherited names, so?fields=constructorwould pass the allowlist and return the whole record,internalNotesincluded.parseWidthaccepts only the whole numbers 48, 96 and 192 and answers anything else (abc,-5,96.5,1e9) with a400; the GraphQL resolver applies the same width check to its argument.shape(a, fields, w)builds one output row. For each field name it splits on the dot:author.namebecomesp = 'author',c = 'name';titlehas no dot, socisundefined. For a dotted name,(out[p] ??= {})creates the nested object only ifout.authordoes not exist yet (??=assigns only when the left side isnullorundefined), then setsnameinside it. For a plain name it setsout[p]directly. The two cases are chosen by the ternaryc ? ... : ....- GraphQL setup.
buildSchemareads a schema written in GraphQL's type language and declares which fields exist and their types.rootValuesupplies the data for the top-levelarticlesfield. A resolver is the function that produces the value for one field; herearticlesis a resolver returning the records, andthumbnailUrlis a resolver that receives the query'swidthargument.graphql({ schema, source, rootValue })parses the query text, checks it against the schema, runs the resolvers for only the fields the query selected, and returns{ data: ... }. - HTTP handler.
/v1/articles/fullreturns every field (the "today" baseline),/v1/articlesappliesparseFieldsandshape, and/graphqlreads the POST body and hands the query text tographql().
What the server has to be careful about
Computed fields. thumbnailUrl does not exist in the database; it is built from imageId and a requested width. The field-picking code must still read the source column imageId even though it is never returned, and take parameters (thumb_w in REST, an argument in GraphQL) as part of the request. Allow only a short list of widths (the code above accepts 48, 96 and 192), or a client can ask for thousands of distinct sizes and fill the image cache.
Default fields. When fields is absent, return a small, documented default set, not "everything". If the default were everything, every old client would keep over-fetching; if you later add a field to the default, every client that did not ask for fields gets a bigger payload. Treat the default set as part of the contract and change it only additively and deliberately. In the server above, no fields gives exactly the four list fields.
Allowlist, not blocklist. internalNotes exists on the stored record but is not in the allowlist, so asking for it returns 400. A blocklist leaks any column someone forgets to add to it. Unknown names should fail loudly: silently ignoring them hides typos from the developer. Test the allowlist with inherited names such as constructor and toString as well as with real column names, because a plain property lookup treats them as present.
Caching. For REST GET, the full URL is the cache key (HTTP caches treat different query strings as different entries). Sorting the field list inside the server (as the code above does) makes both orderings return the same body, but a cache keys on the URL as sent, so title,id and id,title are still two cache entries. To collapse them, have the client library always write the fields in sorted order, have the server answer a non-canonical URL with a redirect to the sorted one, or have the CDN normalize the query string. A CDN (content delivery network) hit ratio drops with every distinct field combination, so publish a few named combinations (or sets such as fields=list and fields=detail) and let each screen use one of them. GraphQL queries sent by POST are not cached by a CDN by default; per the GraphQL over HTTP documentation, GET is allowed for queries only, and long query text can exceed URL length limits, so persisted documents are the usual way to get cacheable GET requests. A persisted document means the server stores each approved query ahead of time under a short id, and the client sends GET /graphql?id=abc123 instead of the full query text; the short URL is cacheable and a server can also be configured to refuse any query that is not on its stored list.
Work behind the wire. A thin response does not make the database query thin. If author.name needs a join and the client does not ask for it, skip the join. For a list of authors, load them in one batched query rather than one per row.
Pitfalls
- Letting nested paths like
author.password_hashthrough because the path resolver is generic. - Checking the allowlist with
inor a bare property lookup, which lets inherited names likeconstructorthrough. - Letting one mobile version rely on the default set, then changing the default.
- Returning a different shape (
nullversus missing key) depending on whether a field was requested, which makes clients branch.
Unlock Full Question Bank
Get access to all 12 Backend-for-Frontend and Client-Specific API Design interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.