The mobile team replaces four REST calls with one GraphQL query. The reading list screen now loads in a single round trip, the launch trace looks better, and the change ships.
A month later the backend team reports that the same screen is responsible for a few hundred database reads every time it opens.
Both observations are accurate. GraphQL describes the shape of the data a client wants. The server still has to authorize, fetch, join, and serialize every field in that shape. Fewer requests on the wire says nothing about how much work each one causes, and the query that causes it is written, reviewed, and shipped by the app team.
That is why I think the people writing the query should understand what executes behind it: what a null means, what a partial response looks like, how one innocent nested field multiplies work, and what a retry does to a mutation.
Start with the screen's contract
A reading app shows articles with their authors:
query ReadingList($first: Int!, $after: String) {
articles(first: $first, after: $after) {
edges {
cursor
node {
id
title
author {
id
displayName
}
}
}
pageInfo {
endCursor
hasNextPage
}
}
}The selection set tells the server which fields to return. It does not answer the questions the screen depends on. Can an article arrive without its author? If the author's account was deleted, is there a placeholder or a null? Are unpublished articles removed before pagination or after, leaving short pages? Does the cursor survive an account switch?
Code generation turns the schema into Swift types. It cannot turn these answers into types, because the schema does not contain them. They have to be agreed with whoever owns the resolvers, and written down.
Nullability decides how far a failure spreads
A possible schema:
type Article {
id: ID!
title: String!
author: Author
}
type Author {
id: ID!
displayName: String!
}author is nullable on purpose. It states that an article is still worth showing when its author cannot be loaded.
Consider the alternative, author: Author!. In GraphQL, when a non-null field fails to resolve, the server cannot return null in that position, so the null propagates to the nearest nullable parent. If node is non-null, the edge is lost. If the edges are [ArticleEdge!]!, the whole list is lost. With non-null all the way up, one author lookup that times out sets data to null, and a thirty-article screen becomes an error page.
! does not make the author service more reliable. It decides how large a piece of the response is destroyed when the service fails. I choose nullability by asking which degraded states the product can still present. Making every generated Swift property non-optional is convenient in the view, and that convenience is the worst reason to choose.
HTTP 200 is not a successful screen
A GraphQL response can contain data and errors together:
{
"data": {
"articles": {
"edges": [
{ "node": { "id": "a1", "title": "Actors in practice", "author": { "displayName": "Dana" } } },
{ "node": { "id": "a2", "title": "Keyset pagination", "author": null } }
]
}
},
"errors": [
{ "message": "Author service timed out",
"path": ["articles", "edges", 1, "node", "author"] }
]
}The status is 200. Checking response.statusCode tells you the transport worked. Whether the screen has what it needs is a decision the app has to make, and I make it in one adapter instead of letting each view interpret optionals.
import Foundation
enum PathComponent: Decodable, Equatable, Sendable {
case field(String)
case index(Int)
init(from decoder: any Decoder) throws {
let container = try decoder.singleValueContainer()
if let index = try? container.decode(Int.self) {
self = .index(index)
} else {
self = .field(try container.decode(String.self))
}
}
}
struct GraphQLError: Decodable, Sendable {
struct Extensions: Decodable, Sendable {
let code: String?
}
let message: String
let path: [PathComponent]?
let extensions: Extensions?
}
struct GraphQLResponse<Payload: Decodable & Sendable>: Decodable, Sendable {
let data: Payload?
let errors: [GraphQLError]?
}
struct ReadingListData: Decodable, Sendable {
struct Connection: Decodable, Sendable { let edges: [Edge] }
struct Edge: Decodable, Sendable { let node: Node }
struct Node: Decodable, Sendable {
let id: String
let title: String
let author: Author?
}
struct Author: Decodable, Sendable { let displayName: String }
let articles: Connection?
}The path is an array of field names and list indices, which is why PathComponent decodes either. The extensions.code field is a widely used server convention, not part of the GraphQL specification, so confirm what your server actually sends before relying on it.
With the envelope decoded, the adapter states the product's policy:
struct ArticleCard: Identifiable, Equatable, Sendable {
let id: String
let title: String
let authorName: String?
}
struct ReadingListSnapshot: Equatable, Sendable {
let articles: [ArticleCard]
let unavailableAuthorCount: Int
}
enum ReadingListOutcome: Equatable, Sendable {
case complete(ReadingListSnapshot)
case partial(ReadingListSnapshot)
case needsAuthentication
case unavailable
}
func readingListOutcome(
from response: GraphQLResponse<ReadingListData>
) -> ReadingListOutcome {
let errors = response.errors ?? []
if errors.contains(where: { $0.extensions?.code == "UNAUTHENTICATED" }) {
return .needsAuthentication
}
guard let connection = response.data?.articles else {
return .unavailable
}
let cards = connection.edges.map { edge in
ArticleCard(
id: edge.node.id,
title: edge.node.title,
authorName: edge.node.author?.displayName
)
}
let snapshot = ReadingListSnapshot(
articles: cards,
unavailableAuthorCount: cards.count { $0.authorName == nil }
)
if errors.isEmpty { return .complete(snapshot) }
let authorsAloneFailed = errors.allSatisfy { $0.path?.last == .field("author") }
return authorsAloneFailed ? .partial(snapshot) : .unavailable
}The policy reads top to bottom: an authentication failure outranks everything; no article data means no screen; errors confined to author fields degrade the screen without replacing it; any other error is treated as a failure because nobody has decided it is tolerable.
That first rule deserves emphasis. If the token has expired and the normalized cache still holds yesterday's reading list, rendering the cache as if it were a fresh authorized result is a security bug that looks like resilience. Stale content may be shown as stale, to the same account, with a visible sign-in prompt. It must not be presented as the answer to this request.
N+1 is an execution problem
The articles resolver runs one query and returns thirty rows. Then GraphQL resolves author for each article, and a naively written resolver runs one query per article. One plus thirty. Add author { organization { name } } to the selection and it becomes one plus thirty plus thirty. The mobile pull request that added two lines to a .graphql file tripled the database load of the screen, and nothing in the client's tooling reported it.
The standard fix is a loader that collects the keys requested during one step of execution and fetches them in one query. In server-side Swift, the core fits in an actor:
struct AuthorRecord: Equatable, Sendable {
let id: String
let displayName: String
}
actor AuthorLoader {
typealias BatchFetch = @Sendable (
_ tenantID: UUID, _ ids: [String]
) async throws -> [String: AuthorRecord]
private let tenantID: UUID
private let fetch: BatchFetch
private var waiting: [String: [CheckedContinuation<AuthorRecord?, any Error>]] = [:]
private var resolved: [String: AuthorRecord?] = [:]
private var flushScheduled = false
init(tenantID: UUID, fetch: @escaping BatchFetch) {
self.tenantID = tenantID
self.fetch = fetch
}
func load(_ id: String) async throws -> AuthorRecord? {
if let known = resolved[id] { return known }
return try await withCheckedThrowingContinuation { continuation in
waiting[id, default: []].append(continuation)
if !flushScheduled {
flushScheduled = true
Task { await self.flush() }
}
}
}
private func flush() async {
await Task.yield()
let batch = waiting
waiting = [:]
flushScheduled = false
do {
let found = try await fetch(tenantID, Array(batch.keys))
for (id, continuations) in batch {
let record = found[id]
resolved[id] = .some(record)
continuations.forEach { $0.resume(returning: record) }
}
} catch {
for continuations in batch.values {
continuations.forEach { $0.resume(throwing: error) }
}
}
}
}This kernel batches whatever has been queued by the time the flush runs. A production loader flushes at a defined point in execution so that batching does not depend on scheduling, and it caps the batch size. The structure is the part to keep, because each piece corresponds to a correctness rule:
- Results are matched to keys by ID.
SELECT … WHERE id IN (…)returns rows in any order and omits missing ones. A loader that zips results with requested keys by position hands article 7 the author of article 9. - A missing author is a result.
resolved[id] = .some(nil)records "looked up, not found", so the same missing ID is not fetched thirty times. - Every continuation is resumed exactly once, on success and on failure. A leaked continuation is a request that never completes.
- The loader is created per request and holds a tenant. This is the rule with the highest cost when broken. A process-wide loader keyed only by author ID will serve one customer's data to another the first time two tenants share an ID, and it will have excellent benchmark numbers while doing it.
- Authorization still applies to what was loaded. Batching changes how rows are fetched. It does not decide who may see them.
"Use DataLoader" is an implementation suggestion. "No loader cache outlives its request or crosses a tenant" is an invariant, and it is the one I would put in the review checklist.
Authorization belongs where objects are resolved
Hiding a field in the client is not access control, and neither is removing a button. The server derives identity from the session and enforces access at the point where domain objects are loaded, so that every route to an object applies the same rule.
That last clause is where GraphQL differs from a set of REST endpoints. The same Article can be reached through articles, through node(id:), through search, through author { articles }, and through a mutation's return value. A filter on the top-level list protects one of five paths. Put the check in the function that loads an article for a viewer, and make every resolver go through it.
Treat IDs as identifiers. A global ID that base64-decodes to Article:8431 is guessable, and knowing it must grant nothing. Error messages need the same care: "not found" for something the viewer may not see, never "forbidden", unless revealing existence is acceptable.
Bound the cost of a query
Nested connections multiply:
query {
projects(first: 50) {
nodes {
articles(first: 100) {
nodes {
comments(first: 100) {
nodes { id }
}
}
}
}
}
}At the stated page sizes this asks for up to 50 × 100 × 100 = 500,000 comment nodes. The real cost depends on the data and on batching, but the upper bound is what an attacker, or an enthusiastic feature, will reach.
The server needs limits that do not depend on the client behaving: a maximum page size per connection, a depth limit, a complexity budget computed from the query before execution, and a timeout. For a first-party app, persisted operations go further: the server accepts only the operation hashes shipped by released builds, which turns "arbitrary queries" into "a reviewed list". That constrains what can be asked. It replaces neither authorization nor input validation.
On the app side, the matching habit is to treat a change to a .graphql file like a change to a SQL query: someone looks at the resolver count and the database round trips it produces before it merges.
Mutations need an answer to "did it happen?"
The app sends createExport, the connection drops, and the request times out. The server may have created the export, charged for it, and failed only to deliver the response. GraphQL does not remove that uncertainty; no protocol does.
If repeating the mutation would be harmful, send an idempotency key generated once per user intent and reused on every retry of that intent. The server binds the key to the authenticated principal and the operation, stores the outcome in the same transaction as the effect, returns the stored outcome when the key is seen again, and rejects the key if it arrives with different arguments. The client's part is small and easy to get wrong: the key must be created when the user taps the button, not inside the function that performs the network call, or every retry gets a fresh key and the mechanism does nothing.
One specification detail is often over-read. Top-level mutation fields in a single operation execute serially. That says nothing about two requests from two devices, and nothing about atomicity across the systems a resolver touches.
Cache identity includes the account
Normalized client caches merge objects from different responses by key, usually type name plus ID. Two questions decide whether that is safe. Is the ID unique across everything the cache will ever hold? And can the same ID have different visible fields for different viewers, as with an Article whose internalNotes only editors receive?
On sign-out or account switch, clear the cache or partition it by account before the next screen renders. A correct network response arriving half a second later cannot undo a private field that was already drawn from the previous account's cache.
Optimistic updates need the same discipline as any optimistic UI: the pending change is kept apart from the server's result, and a failure removes it visibly instead of leaving the cache claiming something the server never accepted.
Verify the work, not only the shape
Schema validation and generated types catch structural drift: a renamed field fails the build. They do not catch semantic drift, where the field is still there and now means something else or costs ten times more. For that:
- record resolver counts and database round trips per operation in a test environment, and fail the build when a known operation exceeds its budget;
- decode recorded responses containing
errorsalongsidedataand assert the outcome the product expects, as in the JSON above; - force a non-null field to fail and check how much of the response disappears;
- run the loader with two tenants sharing an ID;
- send the same mutation twice with one idempotency key and count the effects;
- switch accounts with a warm cache and inspect the first frame.
What to ask of your own client
- For each nullable field you render, what does the screen show when it is null because of an error?
- Where is
errorsinspected, and is it one place? - Who reviews the server cost of a query change?
- Is the idempotency key created at the point of user intent?
- What is in the normalized cache during the first frame after an account switch?
GraphQL gives the app a precise way to ask for data. It leaves the cost of the answer, and the guarantees behind it, for both teams to understand.
References
- GraphQL specification: Handling execution errors
- GraphQL: Execution
- GraphQL: Response
- GraphQL: Authorization
- GraphQL: Security
- DataLoader reference implementation
Related editions
- Edition 28 · From Swift to SQL: Preserving the Meaning of Your Query
- Edition 21 · Your Protocol Is Not an Architecture
- Edition 30 · StoreKit 2: Entitlements, Restoration, and Failure Recovery
If this edition sharpened your next review, you can buy me a coffee.