GraphQL in .NET with Hot Chocolate
On this page
Learning Objective
Explain what GraphQL solves and what it costs compared with REST, build a schema with Hot Chocolate and batch data access with DataLoader, and apply the depth, cost, authorization, and introspection controls that keep a GraphQL endpoint safe.
Concept Explanation
GraphQL is a query language and runtime for APIs, created at Facebook and open-sourced in 2015. Instead of many endpoints that each return a fixed shape, a GraphQL API exposes a typed schema and a single endpoint, and the client sends a query describing exactly the fields it wants, including nested relationships. That helps clients that need many shapes of the same data, such as a mobile app and a web dashboard, and it removes the round trips that a REST client makes to assemble a screen. It also strongly types the contract, and tools can generate TypeScript types from the schema, much like the OpenAPI flow of Day 30.
The costs are real and are often underestimated. Because clients compose their own queries, the server no longer controls the shape of the work: one query can request deeply nested data that produces enormous database load. HTTP caching mostly stops working, since everything is a POST to one URL, error handling moves inside a 200 response, and the tooling for rate limiting, logging, and monitoring must understand queries, not URLs. For a team with one web client and a well-designed REST API, GraphQL is often more complexity than benefit. It pays off where many clients with different needs share a graph of data, or where a backend-for-frontend aggregates many services.
Hot Chocolate is the main GraphQL server for .NET. You define types in C# and the schema is generated, resolvers fetch the data, and it integrates with ASP.NET Core authorization and Entity Framework Core through projections, filtering, and sorting. The classic performance trap is the same N+1 problem from Day 35: resolving each project's owner in a list of projects triggers one query per project. The DataLoader pattern solves it by collecting all the keys requested during one execution and fetching them in a single batched query, then returning each caller its own result.
Security needs deliberate attention because the client controls the query. Limit query depth so a self-referencing query cannot nest a hundred levels, and set a cost limit that assigns a cost to fields and rejects queries that exceed a budget. Limit page sizes on every list field. Disable introspection for public production endpoints, or at least do not treat the schema as secret, since hiding it is not a defense. Authorize at the field and resolver level, since the data graph exposes relationships that a route-based check would not see, and never expose entity classes directly, for the same reasons as Day 23. Beware of aliases and batching, which allow one request to run the same expensive or sensitive operation many times, such as a login mutation with a hundred guesses, so rate limit by cost and not just by request. Mask exception details in responses, and consider persisted queries, where the server only runs pre-registered queries, which removes arbitrary query risk for first-party clients.
| Aspect | REST | GraphQL |
|---|---|---|
| Shape of a response | Fixed by the endpoint | Chosen by the client's query |
| Round trips per screen | Often several | Usually one |
| HTTP caching | Natural, by URL | Difficult, mostly POST to one endpoint |
| Cost of a request | Predictable per endpoint | Varies by query, must be limited |
| N+1 problem | In the server's own queries | In resolvers, solved with DataLoader |
| Main extra defenses | Rate limits, validation | Depth and cost limits, field authorization, persisted queries |
Worked Example: A Hot Chocolate Schema with DataLoader, Authorization and Limits
The code defines types, a batched loader, and the server configuration with limits.
// Types are projections of the domain, not the EF entities themselves.
public sealed record ProjectType(int Id, string Name, int OwnerId);
public sealed record UserType(int Id, string DisplayName);
public sealed class Query
{
[Authorize] // the endpoint is never anonymous
[UsePaging(MaxPageSize = 50, DefaultPageSize = 20)] // no unbounded lists
public IQueryable<ProjectType> GetProjects(AppDb db, ITenantContext tenant) =>
db.Projects.AsNoTracking().Where(p => p.TenantId == tenant.TenantId) // tenant filter in the resolver
.Select(p => new ProjectType(p.Id, p.Name, p.OwnerId));
}
public sealed class ProjectTypeExtensions
{
// Without a DataLoader, a list of 50 projects would run 50 owner queries (the N+1 problem).
public async Task<UserType?> GetOwner([Parent] ProjectType project, UserByIdDataLoader users, CancellationToken ct) =>
await users.LoadAsync(project.OwnerId, ct);
}
public sealed class UserByIdDataLoader : BatchDataLoader<int, UserType>
{
private readonly IDbContextFactory<AppDb> _factory;
public UserByIdDataLoader(IDbContextFactory<AppDb> factory, IBatchScheduler scheduler, DataLoaderOptions? options = null)
: base(scheduler, options) => _factory = factory;
// One query for all owners requested during this execution.
protected override async Task<IReadOnlyDictionary<int, UserType>> LoadBatchAsync(IReadOnlyList<int> keys, CancellationToken ct)
{
await using var db = await _factory.CreateDbContextAsync(ct);
return await db.Users.AsNoTracking().Where(u => keys.Contains(u.Id))
.Select(u => new UserType(u.Id, u.DisplayName)).ToDictionaryAsync(u => u.Id, ct);
}
}// Server configuration: authorization, limits, and quiet errors.
builder.Services
.AddGraphQLServer()
.AddQueryType<Query>()
.AddTypeExtension<ProjectTypeExtensions>()
.AddDataLoader<UserByIdDataLoader>()
.AddAuthorization()
.AddFiltering().AddSorting()
.AddMaxExecutionDepthRule(10) // reject deeply nested queries
.ModifyCostOptions(o => { o.MaxFieldCost = 2_000; o.MaxTypeCost = 2_000; o.EnforceCostLimits = true; }) // recent versions
.AllowIntrospection(builder.Environment.IsDevelopment()) // not a secret-keeper, just less to enumerate
.ModifyRequestOptions(o => o.IncludeExceptionDetails = builder.Environment.IsDevelopment());
builder.Services.AddDbContextFactory<AppDb>(o => o.UseSqlServer(cs)); // a factory: DataLoaders run concurrently
app.MapGraphQL("/graphql").RequireAuthorization().RequireRateLimiting("graphql");# Alias abuse: one HTTP request, one hundred password guesses. Cost limits and per-operation rate limiting must count this.
mutation {
a1: login(email: "x@example.com", password: "guess1") { token }
a2: login(email: "x@example.com", password: "guess2") { token }
# ...repeated
}// First-party clients can use persisted queries: only a registered id is sent, so the server can refuse arbitrary query text.
const res = await fetch('/graphql', {
method: 'POST', credentials: 'include',
headers: { 'Content-Type': 'application/json', 'X-CSRF': '1' },
body: JSON.stringify({ id: 'projects-list-v3', variables: { first: 20 } }),
});Add a test that sends a query nested beyond the limit and one that asks for a page of a thousand items, and assert both are rejected. Those two tests capture most of what makes a GraphQL endpoint different from a REST one.
Real-World Examples
- GitHub's public GraphQL API documents node limits and a points-based rate limit, so that a single query cannot request an unbounded amount of data. Its design shows the standard approach for public GraphQL APIs: limit by estimated cost, cap page sizes, and require authentication.
- Facebook developed GraphQL internally from 2012 to solve the problem of mobile clients needing to fetch many differently shaped pieces of data over slow connections, and released it publicly in 2015. The original motivation, many clients and slow networks, is a good test of whether the trade-off fits your own product.
Review Questions & Answers
Resolving a relationship for each item in a list triggers one database query per item, the N+1 problem. A DataLoader collects the keys requested during an execution and loads them in one batched query, then hands each resolver its own result.
The client writes the query, so a caller can request deeply nested or very large results that put heavy load on the database, while REST endpoints have fixed shapes chosen by the server. Limits put an upper bound on the work one request can demand.
A single request can include the same operation many times under different aliases, for example many login attempts, bypassing a limit that counts requests. Rate limiting and cost analysis must count operations inside the request, not only HTTP requests.
Attackers can often infer the schema from error messages and suggestions, and hiding the schema does not enforce access control. It reduces casual enumeration, but real protection comes from authentication, field-level authorization, and cost limits.