What it actually is
AWS AppSync started life in 2018 as a managed GraphQL endpoint: you upload a schema, attach a resolver to each field, and AppSync runs the query against DynamoDB, Lambda, an HTTP endpoint or a database for you. The developer guide is now split in two, and the second half matters as much as the first. AppSync Events is a serverless WebSocket pub/sub API with no schema at all: clients connect, subscribe to channels such as /notes/team-a, and anything published to that channel fans out to every subscriber. Same console, same billing page, same appsync boto3 client, two different products.
The mental model the docs bury is about where real-time comes from. In AppSync GraphQL, a subscription is not a change feed on your data. The developer guide says it plainly: subscriptions "are invoked as a response to a mutation". The real-time engine watches the mutations that pass through AppSync and pushes the mutation's result to matching subscribers. It never looks at the table. If a batch job, a Lambda, or another service writes the same item straight into DynamoDB, nothing travels down the WebSocket, because nothing passed through the front door. Everybody learns this once, usually in production, and the build below makes you learn it on purpose.
AppSync Events removes the pretence. There is no data source behind a channel unless you add one. You publish an event, it is broadcast. If you want a database write to reach browsers, something has to publish, and you decide what.
The model
GraphQL APIs. An API has a schema (uploaded with StartSchemaCreation, asynchronous, capped at 1 MB), one or more data sources, and resolvers. Data source types in the current API are AWS_LAMBDA, AMAZON_DYNAMODB, AMAZON_OPENSEARCH_SERVICE, HTTP, RELATIONAL_DATABASE (Aurora through the Data API), AMAZON_EVENTBRIDGE, AMAZON_BEDROCK_RUNTIME and NONE. A unit resolver binds one field to one data source; a pipeline resolver runs up to 10 functions in sequence and shares state through ctx.stash. Resolvers are written in APPSYNC_JS (runtime version 1.0.0) or in legacy VTL templates.
APPSYNC_JS is not Node. It is an ES6-like subset that AppSync evaluates itself. Your code never does I/O: the request function returns a description of the call (a DynamoDB GetItem, an HTTP request), AppSync executes it, and the response function shapes ctx.result. The docs list what is missing, and it is a real list: no try/catch/throw, no while or C-style for loops (for-of is fine), no promises or async, no network or file access, no ++. You signal errors with util.error() and keep going with util.appendError(). Helpers come from @aws-appsync/utils and the @aws-appsync/utils/dynamodb module (get, put, update, remove, scan, sync).
Subscriptions. A subscription field carries @aws_subscribe(mutations: [...]) and must return the same type as those mutations. Arguments on the subscription act as filters (onAddNote(author: "houssem") only receives notes from that author), and enhanced filtering lets a subscription resolver set richer rules with extensions.setSubscriptionFilter, with operators such as eq, ge, in and or groups. The transport is pure WebSockets with the graphql-ws subprotocol (AppSync's own dialect: start, start_ack, data, ka); MQTT over WebSockets was retired in January 2022.
Event APIs. An Event API has channel namespaces, and a namespace is the first segment of every channel path: namespace notes owns /notes/team-a, /notes/team-a/alerts and so on. Channels are created on demand, have at most 5 segments of up to 50 characters, and subscribers can use a trailing wildcard such as /notes/*. Each namespace can carry onPublish and onSubscribe handlers in APPSYNC_JS that filter, transform or reject events, and since April 2025 those handlers can call data sources (DynamoDB, Lambda, Aurora and others), or route directly to a Lambda function with no handler code. Publishing works over HTTP (POST https://<http-domain>/event, up to 5 events per request) or, since March 2025, over the same WebSocket you subscribe on.
Auth. Both products support API_KEY, AWS_IAM, AMAZON_COGNITO_USER_POOLS, OPENID_CONNECT and AWS_LAMBDA, and both let you combine several. Event APIs set connection, publish and subscribe auth separately, which is exactly what you want when browsers may subscribe but only your backend may publish. API keys default to a 7-day expiry and can be set up to 365 days; they are for development and public read-only data, not for identifying anyone.
Who operates what. AWS runs the endpoints, the WebSocket fleet, connection state, fan-out, scaling and resolver execution. You own the schema, resolver code, IAM roles AppSync assumes to reach data sources, auth configuration, and the decision about which writes go through AppSync.
When to use it, when not to
You need | Use | Why |
|---|---|---|
One typed API over several backends, clients that pick their fields | AppSync GraphQL | Schema, resolvers, caching and subscriptions are managed; no GraphQL server to run |
Push to browsers or phones, no schema, many channels | AppSync Events | Channels on demand, wildcard subscriptions, $1 per million operations |
REST or HTTP APIs, request-level throttling plans, usage keys per customer | API Gateway (REST or HTTP API) | AppSync has no usage plans and speaks GraphQL or events, not REST |
You own the WebSocket protocol, route by message body, keep per-connection state | API Gateway WebSocket API | You get raw |
Millions of devices, MQTT, device shadows, offline sessions | AWS IoT Core | Device identity and MQTT semantics, which AppSync Events does not try to offer |
The honest summary: AppSync GraphQL earns its keep when you would otherwise run Apollo Server on Lambda or containers and stitch three data sources behind it. AppSync Events is the default answer to "how do I push a message to every open browser tab" on AWS, and it replaces most hand-built API Gateway WebSocket fan-out loops. Neither is the right tool when your data changes outside the API and you expect clients to hear about it automatically.
What it costs
GraphQL bills three things: $4.00 per million query and mutation operations, $2.00 per million real-time updates, and $0.08 per million connection-minutes, plus standard data transfer. Real-time updates include the outbound broadcasts and WebSocket operations such as connects. Optional caching is a separate hourly instance, from $0.044 per hour for cache.small to $6.775 per hour for cache.12xlarge. Merged APIs bill on the merged API only, with no extra charge for the source APIs.
AppSync Events bills $1.00 per million API operations and $0.08 per million connection-minutes. An "operation" is broad on purpose: each inbound publish, each outbound delivery, each handler invocation, each connect, subscribe and ping counts.
The rule that surprises people applies to both: real-time messages are metered per 5 KB of payload delivered, so an 8 KB message counts as two operations, and a message delivered to 10,000 subscribers is 10,000 outbound operations. Fan-out is the bill. The pricing page's own sports example shows it: 110,000 published events cost $0.11, the 10 million deliveries they produce cost $10.00, out of a $13.01 total.
The free tier gives 250,000 GraphQL operations, 250,000 real-time updates and 600,000 connection-minutes per month for 12 months (Events gets the real-time and connection allowances). Accounts created after July 15, 2025 are on the credit-based free plan instead. Either way, the build below makes a few dozen calls: well under one cent, plus a DynamoDB on-demand table that costs nothing at rest.
The limits that bite
30 seconds, hard. Request execution time is capped at 30 seconds for every AppSync API and cannot be raised. A Lambda resolver that calls a slow model or a slow partner API will time out at the AppSync layer while the Lambda keeps running. Long work goes async: start it in a mutation, publish the result later.
Request tokens, not requests. The throttle is 10,000 request tokens per second per API in the large regions (us-east-1, us-west-2, eu-west-1 and others) and 5,000 elsewhere, adjustable. A token is not a request: heavy requests consume more than one token, so a few expensive queries can throttle you well below 10,000 requests per second. Event APIs have their own 2,000 tokens per second.
Fan-out ceilings. GraphQL accepts 10,000 inbound messages per second per API (each subscription type triggered by a mutation is one) and 1,000,000 outbound messages per second, both adjustable. Event APIs accept 10,000 inbound events and 2,000 new connections per second, with a non-adjustable 25 publish requests per second per WebSocket connection. Subscription payloads stop at 240 KB, publish requests at 1.2 MB and 5 events.
Code and schema sizes. Resolver and handler code is capped at 32 KB, pipelines at 10 functions, responses at 5 MB, schemas at 1 MB, a single request at 10,000 resolver executions, and a query at 15,000 tokens. None of these are adjustable, so a schema generated from a large data model can hit the 1 MB ceiling before it hits anything else.
Connections live 24 hours. Both WebSocket protocols close connections after 24 hours and send a keep-alive (ka) roughly every minute; the connection_ack tells you the timeout (300,000 ms in the docs' examples). Clients that do not reconnect with jittered backoff will silently stop receiving.
The front door. Already covered, worth repeating: GraphQL subscriptions only see mutations that AppSync executes. Writes from DynamoDB Streams consumers, batch jobs, or other services are invisible unless something calls a mutation (often a NONE data source mutation that exists only to trigger subscribers) or publishes to an Event API.
Build it
We will build two things in us-east-1 with Python and boto3. First, a GraphQL API named sl-notes with a Note type stored in DynamoDB, JS resolvers for addNote and getNote, and an onAddNote subscription filtered by author. We will subscribe over WebSocket, run a mutation through AppSync, and then write a second note straight into the table to watch the subscription ignore it. Second, an Event API named sl-notes-events with a notes namespace whose onPublish handler stamps valid events and rejects invalid ones, a wildcard subscriber, and an HTTP publisher. Plan for 30 minutes.
Prerequisites. Python 3.10 or later, pip install boto3 websocket-client, AWS credentials for an account where you can create the resources below. The IAM permissions you need are appsync:CreateGraphqlApi, appsync:StartSchemaCreation, appsync:GetSchemaCreationStatus, appsync:CreateApiKey, appsync:CreateDataSource, appsync:CreateResolver, appsync:CreateApi, appsync:CreateChannelNamespace, appsync:DeleteGraphqlApi, appsync:DeleteApi, dynamodb:CreateTable, dynamodb:DescribeTable, dynamodb:PutItem, dynamodb:DeleteTable, iam:CreateRole, iam:PutRolePolicy, iam:PassRole (on the data source role), iam:DeleteRolePolicy and iam:DeleteRole. Cost of following along: under one cent.
Every script imports this. The endpoints helper normalizes the endpoint maps AppSync returns (uris for GraphQL, dns for Event APIs) so key casing never bites you.
import base64, json, pathlib
import boto3
REGION = "us-east-1"
TABLE = "sl-appsync-notes"
ROLE = "sl-appsync-notes-ds-role"
STATE = pathlib.Path("state.json")
appsync = boto3.client("appsync", region_name=REGION)
ddb = boto3.client("dynamodb", region_name=REGION)
iam = boto3.client("iam")
def save(**kv):
s = load(); s.update(kv); STATE.write_text(json.dumps(s, indent=2))
def load():
return json.loads(STATE.read_text()) if STATE.exists() else {}
def b64url(obj):
raw = base64.urlsafe_b64encode(json.dumps(obj).encode()).decode()
return raw.rstrip("=")
def endpoints(m):
"""Normalize the endpoint map AppSync returns (keys like HTTP/REALTIME)."""
return {k.upper(): v for k, v in m.items()}
Step 2: table, role, API, schema, resolvers
This is the whole GraphQL backend. The table has one key, id. The role lets AppSync call GetItem and PutItem on that table and nothing else. The schema declares onAddNote with @aws_subscribe(mutations: ["addNote"]), which is the only link between writes and real-time in this API.
import json, time
from common import *
SCHEMA = """
type Note { id: ID! text: String! author: String! createdAt: AWSDateTime! }
type Query { getNote(id: ID!): Note }
type Mutation { addNote(text: String!, author: String!): Note }
type Subscription {
onAddNote(author: String): Note @aws_subscribe(mutations: ["addNote"])
}
schema { query: Query mutation: Mutation subscription: Subscription }
"""
ADD_NOTE = """
import { util } from '@aws-appsync/utils';
import * as ddb from '@aws-appsync/utils/dynamodb';
export function request(ctx) {
const item = { ...ctx.args, createdAt: util.time.nowISO8601() };
return ddb.put({ key: { id: util.autoId() }, item });
}
export const response = (ctx) => ctx.result;
"""
GET_NOTE = """
import * as ddb from '@aws-appsync/utils/dynamodb';
export const request = (ctx) => ddb.get({ key: { id: ctx.args.id } });
export const response = (ctx) => ctx.result;
"""
# 1. The table: on-demand, one partition key.
ddb.create_table(TableName=TABLE, BillingMode="PAY_PER_REQUEST",
AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}],
KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}])
ddb.get_waiter("table_exists").wait(TableName=TABLE)
table_arn = ddb.describe_table(TableName=TABLE)["Table"]["TableArn"]
# 2. The role AppSync assumes to reach the table.
role_arn = iam.create_role(RoleName=ROLE, AssumeRolePolicyDocument=json.dumps({
"Version": "2012-10-17", "Statement": [{"Effect": "Allow",
"Principal": {"Service": "appsync.amazonaws.com"}, "Action": "sts:AssumeRole"}]}))["Role"]["Arn"]
iam.put_role_policy(RoleName=ROLE, PolicyName="notes-table", PolicyDocument=json.dumps({
"Version": "2012-10-17", "Statement": [{"Effect": "Allow",
"Action": ["dynamodb:GetItem", "dynamodb:PutItem"], "Resource": table_arn}]}))
time.sleep(10) # IAM is eventually consistent
# 3. The API, its schema, and a key.
api = appsync.create_graphql_api(name="sl-notes", authenticationType="API_KEY")["graphqlApi"]
api_id = api["apiId"]
appsync.start_schema_creation(apiId=api_id, definition=SCHEMA.encode())
while (st := appsync.get_schema_creation_status(apiId=api_id))["status"] == "PROCESSING":
time.sleep(2)
assert st["status"] in ("ACTIVE", "SUCCESS"), st
key = appsync.create_api_key(apiId=api_id, expires=int(time.time()) + 2 * 86400)["apiKey"]["id"]
# 4. Data source + two JS unit resolvers.
appsync.create_data_source(apiId=api_id, name="NotesTable", type="AMAZON_DYNAMODB",
serviceRoleArn=role_arn, dynamodbConfig={"tableName": TABLE, "awsRegion": REGION})
for type_name, field, code in [("Mutation", "addNote", ADD_NOTE), ("Query", "getNote", GET_NOTE)]:
appsync.create_resolver(apiId=api_id, typeName=type_name, fieldName=field,
dataSourceName="NotesTable", kind="UNIT", code=code,
runtime={"name": "APPSYNC_JS", "runtimeVersion": "1.0.0"})
uris = endpoints(api["uris"])
save(gql_api_id=api_id, gql_url=uris["GRAPHQL"], gql_realtime=uris["REALTIME"], gql_key=key)
print(json.dumps(load(), indent=2))
Look at the addNote resolver. The request function does not write anything: it returns a PutItem description built by ddb.put, with a key from util.autoId() and a timestamp from util.time.nowISO8601(). AppSync executes it with the role, and response hands back ctx.result, the item that was written. That result is also what subscribers receive, filtered down to the fields they selected. Run python setup_graphql.py; it prints the API ID, the two endpoints and the key, and writes them to state.json.
Step 3: subscribe over WebSocket
AppSync GraphQL speaks its own dialect of graphql-ws. The auth object (host plus API key) goes base64-encoded into the header query parameter, payload=e30= is base64 for {}, and the subscription itself is sent as a start message whose data is a JSON string.
import json, sys, uuid, base64
from urllib.parse import urlparse
import websocket # pip install websocket-client
from common import load
s = load()
host = urlparse(s["gql_url"]).netloc
auth = {"host": host, "x-api-key": s["gql_key"]}
header = base64.b64encode(json.dumps(auth).encode()).decode()
ws = websocket.create_connection(f'{s["gql_realtime"]}?header={header}&payload=e30=',
subprotocols=["graphql-ws"])
ws.send(json.dumps({"type": "connection_init"}))
print("<-", ws.recv()) # connection_ack with connectionTimeoutMs
author = sys.argv[1] if len(sys.argv) > 1 else "houssem"
query = "subscription S($a: String) { onAddNote(author: $a) { id text author createdAt } }"
ws.send(json.dumps({"id": str(uuid.uuid4()), "type": "start", "payload": {
"data": json.dumps({"query": query, "variables": {"a": author}}),
"extensions": {"authorization": auth}}}))
while True:
msg = json.loads(ws.recv())
if msg["type"] == "ka":
continue
print("<-", json.dumps(msg))
Run python gql_subscribe.py houssem in one terminal and leave it open. You should see a connection_ack with a connectionTimeoutMs, then a start_ack for your subscription ID, then keep-alives that the loop swallows.
Step 4: one write through the front door, one around it
import json, sys, urllib.request
from common import load, ddb, TABLE
s = load()
def gql(query, variables):
req = urllib.request.Request(s["gql_url"], method="POST",
data=json.dumps({"query": query, "variables": variables}).encode(),
headers={"content-type": "application/json", "x-api-key": s["gql_key"]})
return json.load(urllib.request.urlopen(req))
author = sys.argv[1] if len(sys.argv) > 1 else "houssem"
out = gql("mutation M($t: String!, $a: String!) { addNote(text: $t, author: $a) { id text author createdAt } }",
{"t": "written through AppSync", "a": author})
print("mutation ->", json.dumps(out))
note_id = out["data"]["addNote"]["id"]
print("query ->", json.dumps(gql("query Q($id: ID!) { getNote(id: $id) { id text } }", {"id": note_id})))
# The control experiment: same table, same shape, no AppSync in the path.
ddb.put_item(TableName=TABLE, Item={"id": {"S": "direct-1"}, "text": {"S": "written straight to DynamoDB"},
"author": {"S": author}, "createdAt": {"S": "2026-11-21T00:00:00Z"}})
print("direct put_item done (watch the subscriber: nothing arrives)")
Run python gql_mutate.py houssem in a second terminal. The mutation returns the new note with its generated ID and timestamp, the query reads it back, and then the script calls put_item on the same table with an item of exactly the same shape.
Verify it works
In the subscriber terminal you should see exactly one data message, shaped like {"type": "data", "id": "<your subscription id>", "payload": {"data": {"onAddNote": {"id": "...", "text": "written through AppSync", "author": "houssem", ...}}}}. The note written with put_item never shows up, even though aws dynamodb scan --table-name sl-appsync-notes lists both items. That is the front door rule, observed rather than read.
Now try the filter: run python gql_mutate.py someone-else while the subscriber is still filtering on houssem. Nothing arrives, because the subscription argument acts as a filter. Stop the subscriber with Ctrl+C.
Step 5: the same broadcast with an Event API
The Event API needs no schema, no table and no role. One namespace, one handler, one key:
import json, time
from common import *
HANDLER = """
import { util } from '@aws-appsync/utils';
export function onPublish(ctx) {
return ctx.events.map((e) => {
if (!e.payload.text) {
return { id: e.id, payload: e.payload, error: 'text is required' };
}
return { id: e.id, payload: { ...e.payload, channel: ctx.info.channel.path, at: util.time.nowISO8601() } };
});
}
"""
key_mode = [{"authType": "API_KEY"}]
api = appsync.create_api(name="sl-notes-events", eventConfig={
"authProviders": key_mode, "connectionAuthModes": key_mode,
"defaultPublishAuthModes": key_mode, "defaultSubscribeAuthModes": key_mode})["api"]
api_id = api["apiId"]
appsync.create_channel_namespace(apiId=api_id, name="notes", codeHandlers=HANDLER)
key = appsync.create_api_key(apiId=api_id, expires=int(time.time()) + 2 * 86400)["apiKey"]["id"]
dns = endpoints(api["dns"])
save(ev_api_id=api_id, ev_http=dns["HTTP"], ev_realtime=dns["REALTIME"], ev_key=key)
print(json.dumps(load(), indent=2))
The handler receives a batch of events in ctx.events, each with an id and a parsed payload. Returning an event broadcasts it; returning it with an error property drops it and reports the failure to the publisher; returning [] drops everything. The { ...e.payload, ... } spread adds the channel path and a server timestamp, so clients never have to trust the publisher's clock.
Run python setup_events.py, then the demo, which starts a wildcard subscriber on /notes/* in a background thread and publishes two events to notes/team-a over HTTP:
import json, threading, time, urllib.request, uuid
import websocket
from common import load, b64url
s = load()
auth = {"host": s["ev_http"], "x-api-key": s["ev_key"]}
def subscriber():
ws = websocket.create_connection(f'wss://{s["ev_realtime"]}/event/realtime',
subprotocols=["aws-appsync-event-ws", "header-" + b64url(auth)])
ws.send(json.dumps({"type": "connection_init"}))
print("sub <-", ws.recv())
ws.send(json.dumps({"type": "subscribe", "id": str(uuid.uuid4()),
"channel": "/notes/*", "authorization": auth}))
while True:
msg = json.loads(ws.recv())
if msg["type"] != "ka":
print("sub <-", json.dumps(msg))
threading.Thread(target=subscriber, daemon=True).start()
time.sleep(3)
body = {"channel": "notes/team-a", "events": [
json.dumps({"text": "deploy finished", "by": "ci"}),
json.dumps({"by": "ci"}), # no text: the handler rejects it
]}
req = urllib.request.Request(f'https://{s["ev_http"]}/event', method="POST",
data=json.dumps(body).encode(), headers={"content-type": "application/json", "x-api-key": s["ev_key"]})
print("pub ->", urllib.request.urlopen(req).read().decode())
time.sleep(3)
Note the protocol differences from Step 3: the subprotocol is aws-appsync-event-ws, the auth object travels as a second subprotocol header-<base64url> with the padding stripped, the endpoint path is /event/realtime, and each published event is itself a JSON string inside the events array.
Verify: the subscriber prints a single data message whose event contains deploy finished with the channel and at fields the handler added. The event without text never reaches the subscriber, and the printed publish response shows how each of the two events fared.
When it breaks
UnauthorizedException or a WebSocket closed with 401. On GraphQL, the host in the auth object must be the API host (<id>.appsync-api.<region>.amazonaws.com), not the realtime host. On Event APIs the same rule holds for the header- subprotocol. An expired API key fails the same way; keys default to 7 days.
BadRequestException with reason CODE_ERROR when creating a resolver or namespace. Your JS used something APPSYNC_JS does not support: try/catch, throw, a while loop, ++, or an async function. The error message names the line. Replace throw with util.error().
Mutation succeeds, subscriber silent. Check, in order: the subscription selection set must be a subset of what the mutation returns; a subscription argument you passed may be filtering the item out (passing author: null means "items without an author", which is different from omitting the argument); and the write may not have gone through a mutation at all.
DynamoDB:AmazonDynamoDBException / access denied in the response. The data source role exists but IAM had not propagated, or the policy names the wrong table ARN. Wait ten seconds and retry; the time.sleep(10) in Step 2 is there for this.
Subscriptions stop after a day, or after a laptop sleeps. That is the 24-hour connection limit and the keep-alive timeout. Production clients (Amplify does this for you) reconnect with jittered exponential backoff and resubscribe.
Event API publish returns 403. Your onPublish handler called util.error(), or the namespace's publish auth mode does not include the mode you used.
Cleanup
from common import *
s = load()
if "gql_api_id" in s: appsync.delete_graphql_api(apiId=s["gql_api_id"])
if "ev_api_id" in s: appsync.delete_api(apiId=s["ev_api_id"])
try:
iam.delete_role_policy(RoleName=ROLE, PolicyName="notes-table")
iam.delete_role(RoleName=ROLE)
except iam.exceptions.NoSuchEntityException:
pass
try:
ddb.delete_table(TableName=TABLE)
ddb.get_waiter("table_not_exists").wait(TableName=TABLE)
except ddb.exceptions.ResourceNotFoundException:
pass
STATE.unlink(missing_ok=True)
print("deleted: GraphQL API, Event API (keys and namespace go with them), role, table")
Run python cleanup.py. Deleting an API deletes its keys, data sources, resolvers and namespaces with it. Confirm with aws appsync list-graphql-apis --query "graphqlApis[].name", aws appsync list-apis --query "apis[].name", aws dynamodb list-tables and aws iam get-role --role-name sl-appsync-notes-ds-role (which should now return NoSuchEntity). Nothing in this build bills at rest except a forgotten cache instance, and we never created one.
For the table design behind the resolvers, see SL#128 on DynamoDB. For routing the same events to other AWS services instead of browsers, see SL#165 on EventBridge, which is also an AppSync data source.

