How to Build Real-Time GraphQL APIs with AWS AppSync: Complete Guide
By Braincuber Team
Published on April 17, 2026
AWS AppSync automatically updates data in web and mobile applications in real time, and synchronizes data for offline users as soon as they reconnect. This complete tutorial shows you how to build serverless GraphQL APIs using AWS AppSync and AWS Amplify. Whether you are building a chat application, collaborative editing tool, or real-time dashboard, AppSync handles the complexity of data synchronization so you can focus on your application logic.
What You'll Learn:
- Understanding AWS AppSync and GraphQL fundamentals
- Step by step guide to creating an AppSync API
- Beginner guide to AWS Amplify CLI setup
- How to model GraphQL relationships (1:1, 1:N, M:N)
- Complete tutorial on GraphQL queries, mutations, and subscriptions
- Implementing real-time updates with GraphQL subscriptions
- Building offline-capable web applications
What is AWS AppSync?
AWS AppSync is a fully managed serverless service that makes it easy to develop GraphQL APIs by handling secure connections, real-time data synchronization, and offline capabilities. With AppSync, you define your data schema once and AppSync automatically generates the resolvers that connect to your data sources.
AppSync supports multiple data sources including Amazon DynamoDB, AWS Lambda, and Amazon Elasticsearch. This flexibility allows you to choose the right data store for your specific use case while maintaining a unified GraphQL interface for your clients.
Real-Time Data Sync
Push updates to connected clients instantly when data changes. No polling or manual refresh needed.
Offline Support
Apps continue working offline and automatically sync when connectivity returns.
Secure Access
Fine-grained authorization controls with Cognito, API keys, or IAM permissions.
Serverless
Fully managed service with automatic scaling. Pay only for requests you use.
Understanding GraphQL with AppSync
GraphQL is a query language for APIs that allows clients to request exactly the data they need. Unlike REST APIs where you get fixed response structures, GraphQL lets you define flexible queries that fetch multiple resources in a single request.
AppSync implements GraphQL with three operation types that map to standard database operations:
| Operation | Purpose | Database Equivalent |
|---|---|---|
| Query | Read data from the API | SELECT |
| Mutation | Create, update, or delete data | INSERT, UPDATE, DELETE |
| Subscription | Receive real-time updates | WebSocket notifications |
Setting Up AWS Amplify CLI
AWS Amplify provides a command-line interface and libraries for building cloud-connected applications. The Amplify CLI makes it easy to create and configure AppSync APIs without navigating multiple AWS services.
Step-by-Step: Installing Amplify CLI
Install Amplify CLI via npm
Run the following command in your terminal to install the Amplify CLI globally:
npm install -g @aws-amplify/cli
amplify configure
Prerequisite
You need an AWS account with appropriate IAM permissions. The amplify configure command will guide you through creating an IAM user with the required permissions for AppSync and related services.
Creating an AppSync API with Amplify
Once Amplify CLI is configured, you can initialize a new project and add the AppSync API. Amplify will automatically create the GraphQL schema, resolvers, and DynamoDB tables.
mkdir my-appsync-project
cd my-appsync-project
amplify init
Adding the GraphQL API
Add API to Amplify
Run the amplify add api command to add a GraphQL API to your project.
Choose API Type
Select GraphQL when prompted to choose between REST and GraphQL API types.
Configure Authentication
Choose Amazon Cognito for authentication to enable user sign-up, sign-in, and secure access control.
Enable Additional Settings
Enable Additional auth providers, Serverless Lambda function authorization, N/A for conflict detection (or choose DynamoDB for advanced scenarios).
Defining Your GraphQL Schema
The GraphQL schema defines the types, queries, mutations, and subscriptions available in your API. When you run amplify add api with the GraphQL option, Amplify generates a schema template that you can customize.
type Note @model @auth(rules: [{ allow: owner }]) {
id: ID!
title: String!
content: String
createdAt: String
updatedAt: String
}
type Query {
getNote(id: ID!): Note
listNotes(filter: ModelNoteFilterInput, limit: Int, nextToken: String): ModelNoteConnection
}
type Mutation {
createNote(input: CreateNoteInput!, condition: ModelNoteConditionInput): Note
updateNote(input: UpdateNoteInput!, condition: ModelNoteConditionInput): Note
deleteNote(input: DeleteNoteInput!, condition: ModelNoteConditionInput): Note
}
type Subscription {
onCreateNote(owner: String): Note @aws_subscribe(mutations: ["createNote"])
onUpdateNote(owner: String): Note @aws_subscribe(mutations: ["updateNote"])
onDeleteNote(owner: String): Note @aws_subscribe(mutations: ["deleteNote"])
}
Modeling GraphQL Relationships
GraphQL schemas can represent complex relationships between data types. Amplify makes it easy to define one-to-one, one-to-many, and many-to-many relationships using directives.
| Relationship | Amplify Directive | Example |
|---|---|---|
| One-to-One (1:1) | @hasOne | User has one Profile |
| One-to-Many (1:N) | @hasMany | Blog has many Posts |
| Many-to-Many (M:N) | @manyToMany | Posts have many Tags |
type Blog @model {
id: ID!
name: String!
posts: [Post] @hasMany(indexName: "byBlog", fields: ["id"])
}
type Post @model {
id: ID!
title: String!
blogID: ID! @index(name: "byBlog")
blog: Blog @belongsTo(fields: ["blogID"])
comments: [Comment] @hasMany(indexName: "byPost", fields: ["id"])
}
type Comment @model {
id: ID!
content: String!
postID: ID! @index(name: "byPost")
post: Post @belongsTo(fields: ["postID"])
}
Implementing GraphQL Queries and Mutations
Once your schema is defined, Amplify automatically generates queries and mutations based on your @model types. You can also define custom queries and mutations for complex operations.
Creating Data with Mutations
import { API, graphqlOperation } from 'aws-amplify';
import { createNote } from './graphql/mutations';
const newNote = {
title: 'My First Note',
content: 'This is the content of my note'
};
const result = await API.graphql(
graphqlOperation(createNote, { input: newNote })
);
console.log('Created note:', result.data.createNote);
Querying Data
import { listNotes, getNote } from './graphql/queries';
// List all notes
const allNotes = await API.graphql(
graphqlOperation(listNotes)
);
console.log('All notes:', allNotes.data.listNotes.items);
// Get a specific note
const specificNote = await API.graphql(
graphqlOperation(getNote, { id: 'note-id-123' })
);
console.log('Specific note:', specificNote.data.getNote);
Real-Time Updates with GraphQL Subscriptions
GraphQL subscriptions enable real-time push notifications to your clients. When data changes on the server, connected clients receive the update instantly without polling.
import { onCreateNote, onUpdateNote, onDeleteNote } from './graphql/subscriptions';
// Subscribe to new notes
const createSubscription = API.graphql(
graphqlOperation(onCreateNote)
).subscribe({
next: ({ provider, value }) => {
console.log('New note created:', value.data.onCreateNote);
},
error: (error) => console.error('Subscription error:', error)
});
// Subscribe to note updates
const updateSubscription = API.graphql(
graphqlOperation(onUpdateNote)
).subscribe({
next: ({ provider, value }) => {
console.log('Note updated:', value.data.onUpdateNote);
},
error: (error) => console.error('Subscription error:', error)
});
// Remember to unsubscribe when done
// createSubscription.unsubscribe();
// updateSubscription.unsubscribe();
Building Offline-Capable Apps
AWS Amplify includes built-in offline support. When using AppSync with Amplify, mutations are automatically queued when offline and synced when connectivity returns.
import Amplify from 'aws-amplify';
Amplify.configure({
Auth: { /* Auth configuration */ },
API: {
GraphQL: {
endpoint: 'https://xxx.appsync-api.us-east-1.amazonaws.com/graphql',
region: 'us-east-1',
defaultAuthMode: 'AMAZON_COGNITO_USER_POOLS',
// Enable offline support
sync: {
maxQueryDepth: 10,
conflictDetection: 'VERSION',
conflictHandler: 'AUTOMERGE'
}
}
}
});
// Mutations automatically queue offline and sync when online
const mutation = API.graphql({
query: createNote,
variables: { input: { title: 'Offline note', content: 'Will sync later' } },
// Track sync status
fetchPolicy: 'network-only'
});
Deploying Your AppSync API
After defining your schema, deploy your API to the cloud using the Amplify CLI. This creates all the necessary AWS resources including AppSync API, DynamoDB tables, and Cognito configuration.
Push Changes to Cloud
Run amplify push to deploy your API and data model to AWS.
Confirm Changes
Review the changes and confirm when prompted. Amplify will create CloudFormation stacks for your resources.
Access Generated Code
Amplify generates client-side code in src/graphql/ including queries, mutations, subscriptions, and type definitions.
amplify push
# Or use shorthand
amplify push -y
Frequently Asked Questions
What is the difference between AWS AppSync and API Gateway for GraphQL?
AppSync is specifically designed for GraphQL with built-in real-time subscriptions, offline sync, and client-generated queries. API Gateway supports REST APIs and WebSocket APIs but lacks native GraphQL support and offline capabilities.
How does AppSync handle data conflicts in offline scenarios?
AppSync uses optimistic locking with version numbers. When conflict detection is enabled, you can choose between AUTOMERGE (let AppSync merge), SERVER_SIDE (server wins), or CLIENT_SIDE (client wins) conflict resolution strategies.
What data sources does AppSync support?
AppSync supports Amazon DynamoDB (NoSQL), AWS Lambda (for custom logic), Amazon Elasticsearch (for full-text search), and HTTP endpoints (for integrating external REST APIs).
How much does AWS AppSync cost?
AppSync pricing is based on requests: $4.00 per million queries and mutations, and $2.00 per million subscription notifications. The free tier includes 600K queries/mutations and 1M subscription notifications per month.
Can I use AppSync without Amplify?
Yes, you can use AppSync directly through the AWS Console, CLI, or SDKs. Amplify CLI simplifies the setup and provides convenient abstractions, but AppSync works independently with any GraphQL client.
Need Help Building Real-Time Apps with AWS AppSync?
Our AWS experts can help you design and implement GraphQL APIs with AppSync. From schema design to real-time subscriptions and offline support, we deliver scalable serverless backends.
