Real-Time Chat with AWS AppSync
Build a live chat feature using GraphQL subscriptions on AWS AppSync.
Building real-time features (chat, live notifications, collaborative editing) traditionally meant standing up and scaling WebSocket infrastructure yourself. AppSync's GraphQL subscriptions handle the WebSocket layer entirely — clients subscribe to a query, and AppSync pushes updates automatically whenever a matching mutation occurs.
The schema-driven model
graphql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
type Message {
id: ID!
roomId: ID!
text: String!
sender: String!
}
type Mutation {
sendMessage(roomId: ID!, text: String!, sender: String!): Message
}
type Subscription {
onNewMessage(roomId: ID!): Message
(mutations: ["sendMessage"])
}The
@aws_subscribe directive links a subscription to the mutation(s) that should trigger it — no custom pub/sub infrastructure to build; AppSync handles matching subscribed clients to relevant mutations and pushing the update over their open WebSocket connection automatically.Resolvers backed by DynamoDB
1
sendMessage mutation → AppSync Resolver → DynamoDB PutItem → triggers matching SubscriptionsA resolver (either a direct DynamoDB integration via VTL/JS resolver, or a Lambda resolver for more complex logic) handles writing the new message; AppSync automatically fans the resulting data out to every client currently subscribed to
onNewMessage for that room.Client-side subscription
javascript
1
2
3
4
5
6
const subscription = client.graphql({
query: onNewMessage,
variables: { roomId: "room-123" }
}).subscribe({
next: ({ data }) => appendMessageToUI(data.onNewMessage)
});The client library manages the WebSocket connection, reconnection on network drops, and re-subscription — application code just reacts to incoming data.
Authorization per field
AppSync supports multiple auth modes simultaneously (IAM, Cognito User Pools, API Key, Lambda authorizers) and lets you apply different modes per field or type — a chat app might require Cognito auth to send messages, while allowing IAM-authenticated backend services to read messages for moderation, all within the same schema.
Why this beats hand-rolled WebSockets via API Gateway
API Gateway's WebSocket APIs give you the raw connection primitive — you still build the routing, connection-tracking, and fan-out logic yourself. AppSync's GraphQL subscription model gives you that fan-out (many clients subscribed to the same data, updated automatically on change) as a built-in feature of the schema, at the cost of committing to GraphQL as your API paradigm rather than plain REST/WebSocket messages.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article