GraphQL in .NET
GraphQL is a query language for APIs that lets clients specify exactly which fields they need, eliminating over-fetching and under-fetching in a single typed contract.
Overview
Hot Chocolate runs a spec-compliant GraphQL server on ASP.NET Core: it builds a strongly typed schema from C# types or explicit descriptors, parses and validates operation documents, executes resolver trees, and returns a response shaped by the selected fields. Queries read, mutations represent state-changing workflows, and subscriptions or incremental delivery use long-lived transports where supported. Flexibility moves substantial responsibility to the server. Every field is an API and authorization boundary; nested selection can multiply database and downstream work; errors may coexist with partial data; HTTP 200 does not imply business success; and schema nullability is a compatibility promise. Production systems use cursor pagination, DataLoader batching, projection with deliberate IQueryable boundaries, depth and cost analysis, persisted or allow-listed operations where appropriate, timeouts, cancellation, response and list bounds, field and object authorization, schema governance, and resolver telemetry. GraphQL works well for client-driven composition across a coherent graph, but simple resource APIs, streaming protocols, files, and broad third-party integration may remain clearer through HTTP resources or other protocols.
What you will learn
- Design a coherent GraphQL schema with stable nullability, naming, pagination, and mutation payloads.
- Understand execution, resolver composition, partial data, and GraphQL error semantics.
- Prevent N+1 access through request-scoped DataLoader batching and appropriate projections.
- Bound depth, cost, pages, lists, variables, time, and response size.
- Authenticate requests and authorize types, fields, resources, tenants, and mutation workflows.
- Test schema compatibility and real GraphQL-over-HTTP selection, paging, errors, and authorization.
Prerequisites
- ASP.NET Core dependency injection, authentication, authorization, and HTTP middleware.
- Database query behavior, asynchronous C#, JSON, and API schema compatibility.
- A .NET 10 SDK to run the Hot Chocolate inventory sample.
When to use GraphQL in .NET
Good fit
- Use GraphQL when several trusted clients need different connected views over one governed domain graph.
- Use cursor pagination and DataLoader when relationships and lists are first-class client needs.
- Use persisted operations when clients and releases can coordinate an allow-listed production contract.
Choose another approach when
- Do not adopt GraphQL only to wrap simple CRUD without a client composition need.
- Do not expose unrestricted nested graphs without cost, depth, list, timeout, and authorization controls.
- Do not return IQueryable across uncontrolled layers or assume projection automatically enforces business security.
- Do not treat introspection, field hiding, or a successful HTTP status as authorization or business success.
Key concepts
The schema defines every type, field, query, mutation, and subscription the API exposes. A resolver is the function that fetches or computes the value for one field — analogous to a controller action but composable and field-scoped.
Queries read data; mutations write data and return the updated state; subscriptions open a WebSocket connection and push updates when server-side state changes — all described in the same schema.
A DataLoader batches individual field-level resolver calls into a single bulk database query per request cycle, preventing the N+1 problem that occurs when each item in a list triggers a separate query.
Clients register query documents at build time and send only a hash at runtime. The server executes only pre-approved queries, reducing payload size, preventing arbitrary query attacks, and enabling query-level caching.
Edges, nodes, cursors, and pageInfo provide a bounded stable list contract without exposing database offsets.
Depth, field weights, list multipliers, and response limits estimate and reject operations that exceed an allowed budget.
A response can contain usable data and field errors together, so clients inspect both rather than only HTTP status.
Additive nullable fields are usually safe; removals, nullability changes, enum additions, and semantic changes require usage evidence and deprecation.
Architecture
The client sends a typed query document; Hot Chocolate validates it against the schema, resolves each field using injected services or DataLoaders, and returns a single JSON response shaped to the query.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
The dedicated inventory catalog uses Hot Chocolate 16 on .NET 10 with a typed query and mutation schema, bounded cursor paging, policy-protected stock changes, stable domain error payloads, development exception detail, and HTTP integration tests that prove selection and authorization behavior.
- 01Model the graph
Define domain-oriented types, stable names, nullability, identifiers, relationships, and ownership rather than mirroring tables.
- 02Register operations
Add query and mutation types explicitly and keep resolvers thin over application services.
- 03Bound lists
Use cursor connections with maximum page size and prohibit unbounded nested collections.
- 04Batch relationships
Use request-scoped DataLoaders keyed by stable identifiers to batch and cache related loads.
- 05Authorize the graph
Authenticate through ASP.NET Core and enforce policy plus resource and tenant checks on sensitive fields and mutations.
- 06Control execution
Set cost, depth, time, cancellation, variable, document, result, and persisted-operation policy.
- 07Govern and verify
Snapshot or inspect the schema, test real operations and negative paths, measure resolvers, and deprecate with usage evidence.
Code example
A code-first query type exposes orders with a DataLoader to batch product lookups — the client gets exactly the fields it asks for and the server makes one product query regardless of how many order lines are returned.
// Schema registration
builder.Services
.AddGraphQLServer()
.AddQueryType<OrderQuery>()
.AddMutationType<OrderMutation>()
.AddSubscriptionType<OrderSubscription>()
.AddProjections()
.AddFiltering()
.AddSorting()
.RegisterDbContext<AppDbContext>();
app.MapGraphQL();
// Query type
public sealed class OrderQuery
{
[UseProjection]
[UseFiltering]
[UseSorting]
public IQueryable<Order> GetOrders(
AppDbContext db) => db.Orders.AsNoTracking();
public async Task<Order?> GetOrderAsync(
Guid id, AppDbContext db,
CancellationToken ct) =>
await db.Orders.FindAsync([id], ct);
}
// DataLoader: batch product loads across all order lines in one request
public sealed class ProductByIdDataLoader(
IProductRepository repo,
IBatchScheduler scheduler,
DataLoaderOptions options)
: BatchDataLoader<Guid, ProductDto>(scheduler, options)
{
protected override async Task<IReadOnlyDictionary<Guid, ProductDto>>
LoadBatchAsync(IReadOnlyList<Guid> keys, CancellationToken ct)
{
var products = await repo.GetByIdsAsync(keys, ct);
return products.ToDictionary(p => p.Id);
}
}
// Resolver using DataLoader on OrderLine type
public sealed class OrderLineType : ObjectType<OrderLine>
{
protected override void Configure(
IObjectTypeDescriptor<OrderLine> descriptor)
{
descriptor
.Field("product")
.ResolveWith<OrderLineResolvers>(r =>
r.GetProductAsync(default!, default!, default!));
}
}
public sealed class OrderLineResolvers
{
public async Task<ProductDto?> GetProductAsync(
[Parent] OrderLine line,
ProductByIdDataLoader loader,
CancellationToken ct) =>
await loader.LoadAsync(line.ProductId, ct);
}Testing strategy
Schema tests and real operation tests cover different failure modes and both are required.
- Snapshot or compare the schema for unintended type, field, argument, enum, and nullability changes.
- Execute GraphQL-over-HTTP requests and assert selected fields, aliases, variables, cursors, pageInfo, and errors.
- Prove anonymous, missing-policy, wrong-tenant, and unauthorized-field behavior.
- Measure repository calls to prove DataLoader prevents N+1 access.
- Reject over-depth, over-cost, over-page, oversized-variable, timeout, and cancelled operations.
- Test partial data, domain mutation errors, concurrency, idempotency, and subscription reconnect where used.
Security considerations
A single endpoint exposes many possible execution plans, so authorization and resource bounds belong inside graph execution.
- Authenticate before execution and authorize sensitive types, fields, mutations, tenants, and loaded resources.
- Apply depth, cost, page, list, variable, document, time, and response-size limits.
- Use persisted or allow-listed operations for controlled clients when arbitrary production queries are unnecessary.
- Restrict introspection and IDE exposure only as defense in depth; do not rely on obscurity.
- Redact exception details, variables, tokens, personal data, and resolver payloads from production logs.
Performance and scalability
Client-selected shape makes workload cost variable and requires resolver-level evidence.
- Batch one-to-many resolver access with request-scoped DataLoaders and stable keys.
- Apply projection, filtering, and sorting only through reviewed database query boundaries.
- Use cursor pagination with maximum page size for every potentially growing list.
- Reject operations beyond measured depth and cost budgets before expensive execution.
- Trace operation name or persisted hash and resolver timing without storing sensitive documents or variables.
- Load-test representative operations, pathological nesting, cache behavior, and downstream fan-out.
Deployment and operations
Schema and operation compatibility must be coordinated with clients, gateways, caches, and observability.
- Publish a schema artifact and run compatibility plus known-operation validation in CI.
- Deploy additive server support before clients use new selections and retain deprecated fields through the announced window.
- Configure production IDE, introspection, persisted operations, exception detail, CORS, and authentication intentionally.
- Set proxy body, timeout, WebSocket, and response limits for the enabled transports.
- Smoke-test query, paging, authorized mutation, denial, cost rejection, and telemetry through the deployed endpoint.
Common problems and fixes
A list query issues hundreds of database calls.
Likely cause: Each child resolver loads related data independently.
Fix: Introduce a request-scoped DataLoader and assert bulk-call count in tests.
Simple queries exhaust CPU or memory.
Likely cause: Nested lists, aliases, fragments, or page sizes bypass useful cost bounds.
Fix: Configure measured depth, cost, list, page, time, and response limits.
The response is HTTP 200 but the operation failed.
Likely cause: GraphQL communicates execution errors in the response body and may include partial data.
Fix: Inspect errors and typed mutation payloads in every client and test.
An authorized user reads another tenant's node.
Likely cause: A resolver checked authentication but not tenant and resource authorization.
Fix: Scope the load and authorize the actual resource at the field or application-service boundary.
A schema change breaks generated clients.
Likely cause: A field, type, nullability, enum, argument, or semantic contract changed incompatibly.
Fix: Restore compatibility, deprecate additively, inspect usage, and enforce schema checks.
Production reveals stack traces or schema tools.
Likely cause: Development exception detail, introspection, or IDE configuration remained enabled.
Fix: Apply an explicit environment exposure policy and verify the deployed endpoint.
Best practices
- Design a coherent domain graph rather than mirroring tables and internal service boundaries.
- Treat nullability, enum values, field semantics, and mutation payloads as compatibility contracts.
- Bound every growing list with cursor pagination and a maximum page size.
- Use request-scoped DataLoaders and call-count tests for related entity loads.
- Enforce measured depth, cost, document, variable, timeout, and response budgets.
- Authenticate requests and authorize fields, tenants, resources, and mutation workflows.
- Use persisted operations for controlled clients when arbitrary queries add no value.
- Publish schema artifacts, observe resolver cost, and deprecate only with usage evidence.
Production checklist
- Schema types, naming, nullability, identifiers, relationships, and ownership are reviewed.
- Every growing list uses bounded cursor pagination.
- DataLoader or equivalent batching prevents N+1 access and is call-count tested.
- Authentication plus field, mutation, tenant, object, and property authorization is negative-tested.
- Depth, cost, page, list, variable, document, timeout, cancellation, and response limits are enforced.
- Schema compatibility, known operations, deprecation, and client usage have CI evidence and owners.
- IDE, introspection, persisted operations, errors, CORS, and transport exposure follow production policy.
- Operation, resolver, database, error, cost, and downstream telemetry is safe and actionable.
Common interview questions
What problem does GraphQL solve that REST does not handle well?
REST endpoints return fixed shapes — clients either get too much data for their needs or must call multiple endpoints and assemble the result. GraphQL lets the client declare exactly which fields it needs in a single request, eliminating over-fetching, under-fetching, and the waterfall of requests common in REST-based mobile applications.
What is the N+1 problem in GraphQL and how does DataLoader solve it?
When resolving a list of items, each item's child fields are resolved individually — a list of 100 orders each triggering a separate product query results in 101 database calls. DataLoader collects all product ID requests made during one execution cycle, issues a single bulk query for all of them, and distributes the results back to each resolver — reducing 101 calls to 2.
When would you choose GraphQL over REST for a .NET API?
GraphQL is a strong fit when multiple clients need different shapes of the same data — a web app, a mobile app, and a BFF — when query flexibility matters more than cache simplicity, or when aggregating data from several services in a single request. REST remains better for simple CRUD resources, public APIs with broad tooling expectations, HTTP caching requirements, and teams less familiar with GraphQL's operational complexity.
Why can GraphQL return HTTP 200 with errors?
Transport succeeded even though one or more fields failed during execution; the response may contain partial data and an errors array that clients must inspect.
How should GraphQL query cost be controlled?
Combine depth, field weights, list multipliers, page limits, timeouts, cancellation, and measured persisted-operation budgets rather than relying on one limit.
Is disabling introspection an authorization control?
No. It reduces casual discovery only; every field and loaded resource still requires server-side authentication, authorization, validation, and bounds.
What makes a GraphQL schema change breaking?
Removing or renaming fields, tightening nullability, changing argument or return types, and changing established semantics can break consumers; even enum additions affect exhaustive clients.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
GraphQL Inventory Catalog
A .NET 10 Hot Chocolate service demonstrating a typed schema, bounded cursor paging, field selection, policy-protected mutation, stable domain errors, and GraphQL-over-HTTP tests.
- Run
dotnet run --project src/GraphQlInventoryCatalog- Test
dotnet test GraphQlInventoryCatalog.slnx