Kinesis Data Streams and AppSync
Overview
Amazon Kinesis Data Streams (KDS) ingests and stores ordered streams of records in real time so multiple consumers can process them, replay them and react within seconds. AWS AppSync is a managed GraphQL (and Pub/Sub) API service that lets clients ask for exactly the data they need from many sources through one endpoint.
Kinesis is like a conveyor belt that does not stop: records ride the belt in order for a retention window, and any number of workers can stand beside it and read from their own position. AppSync is like a concierge who accepts a single detailed request ("give me this user, their last 5 orders and the product names") and gathers the pieces from various departments.
The exam tests shard capacity, partition keys, consumer types, and when to choose Kinesis over SQS, and the basics of GraphQL resolvers and real-time subscriptions.
Key Concepts
- A KDS stream consists of shards: each handles 1 MB/s or 1,000 records/s write and 2 MB/s read (shared by consumers); on-demand mode scales automatically.
- The partition key is hashed to choose a shard; ordering is guaranteed per shard (and so per partition key). Bad keys create hot shards.
- Retention is 24 hours by default, extendable to 365 days; records up to 1 MB.
- Shared throughput consumers (
GetRecords) share 2 MB/s per shard; enhanced fan-out gives each registered consumer a dedicated 2 MB/s over push (HTTP/2) with about 70 ms latency. - ProvisionedThroughputExceededException on writes: use a better partition key, add shards or retry with backoff; use the KPL to batch/aggregate.
- Kinesis Data Firehose (now Amazon Data Firehose) is a near-real-time delivery service to S3, Redshift, OpenSearch and HTTP endpoints with optional Lambda transformation.
- AppSync provides GraphQL queries, mutations and subscriptions (WebSocket real time) with resolvers to DynamoDB, Lambda, HTTP, RDS and OpenSearch.
- AppSync authorisation modes: API key, Cognito, IAM, OIDC, Lambda; supports caching and offline sync with Amplify clients.
Detailed Notes
Kinesis vs SQS
| Aspect | Kinesis Data Streams | SQS |
|---|---|---|
| Model | Ordered log, many consumers | Queue, each message to one consumer |
| Retention | 1-365 days, replayable | Until deleted (max 14 days) |
| Ordering | Per shard | FIFO queues per group |
| Scaling | Shards (or on-demand) | Automatic |
| Consumers | Multiple independent | Competing consumers |
| Use case | Clickstreams, logs, IoT, analytics | Task queues, buffering |
Producing records
import boto3, json
kinesis = boto3.client("kinesis")
kinesis.put_record(
StreamName="clicks",
Data=json.dumps({"user": "u1", "page": "/home"}).encode(),
PartitionKey="u1", # same user -> same shard -> ordered
)
resp = kinesis.put_records(
StreamName="clicks",
Records=[{"Data": b"...", "PartitionKey": f"u{i}"} for i in range(500)],
)
if resp["FailedRecordCount"]:
# retry only the failed entries, with backoff
failed = [r for r in resp["Records"] if "ErrorCode" in r]
PutRecords accepts up to 500 records (5 MB) and can partially fail.
Consuming
- Lambda event source mapping (per-shard, in order, batch, parallelization factor, bisect on error).
- KCL (Kinesis Client Library) coordinates workers with a DynamoDB lease table, checkpointing progress.
- Enhanced fan-out for multiple low-latency consumers.
If a consumer fails to keep up, GetRecords.IteratorAgeMilliseconds rises: add shards, increase parallelization or optimise processing. Reading from the same shard with more than five classic consumers hits the 2 MB/s shared limit; use enhanced fan-out.
aws kinesis create-stream --stream-name clicks \
--stream-mode-details StreamMode=ON_DEMAND
aws kinesis update-shard-count --stream-name clicks \
--target-shard-count 8 --scaling-type UNIFORM_SCALING
Firehose
Firehose buffers by size (1-128 MB) or time (60-900 s) and delivers to destinations with optional Lambda transformation, format conversion (Parquet/ORC) and dynamic partitioning. It has no replay and is fully managed; KDS can be its source.
AppSync basics
A GraphQL schema defines types and operations:
type Order { id: ID! total: Float! items: [Item!]! }
type Query { getOrder(id: ID!): Order }
type Mutation { placeOrder(total: Float!): Order }
type Subscription { onOrderPlaced: Order @aws_subscribe(mutations: ["placeOrder"]) }
Resolvers map fields to data sources. Pipeline resolvers chain several functions. AppSync supports JavaScript resolvers (APPSYNC_JS) and VTL.
| Need | Choose |
|---|---|
| Flexible client-driven queries, mobile apps | AppSync |
| Simple REST integration | API Gateway |
| Real-time updates to many clients | AppSync subscriptions (or API Gateway WebSocket) |
Node.js consumer for Lambda
export const handler = async (event) => {
for (const rec of event.Records) {
const payload = JSON.parse(Buffer.from(rec.kinesis.data, "base64").toString());
console.log(rec.kinesis.partitionKey, rec.kinesis.sequenceNumber, payload);
}
};
Kinesis record data is base64 encoded in Lambda events.
Ordering and duplicates
Producer retries can create duplicates, so consumers should be idempotent (use sequence numbers or an idempotency key).
Kinesis family and capacity
| Service | Purpose | Notes |
|---|---|---|
| Kinesis Data Streams | Ordered, replayable stream per shard | Provisioned (1 MB/s in, 2 MB/s out per shard) or on-demand capacity |
| Data Firehose | Load streams into S3, Redshift, OpenSearch, HTTP | Near-real-time buffering, optional Lambda transform, no consumer code |
| Managed Apache Flink | Stateful stream analytics | SQL or Java/Python |
A producer sends up to 1,000 records or 5 MB per PutRecords call, each record up to 1 MB. Data is retained 24 hours by default and up to 365 days. The partition key is hashed to choose the shard, so high-cardinality keys spread load.
import json, boto3
kinesis = boto3.client("kinesis")
resp = kinesis.put_records(StreamName="clicks", Records=[
{"Data": json.dumps(e).encode(), "PartitionKey": e["deviceId"]} for e in events])
if resp["FailedRecordCount"]:
retry = [r for r, res in zip(events, resp["Records"]) if "ErrorCode" in res] # resend only failures
Reading uses the KCL, Lambda event source mappings or enhanced fan-out (dedicated 2 MB/s per consumer, pushed over HTTP/2). ProvisionedThroughputExceededException on a producer means a hot shard: use a better key, add shards or switch to on-demand. Consumer lag appears as GetRecords.IteratorAgeMilliseconds.
AppSync essentials
AppSync is managed GraphQL. A schema defines types, resolvers (VTL or JavaScript) connect fields to data sources (DynamoDB, Lambda, OpenSearch, HTTP, RDS), and subscriptions push mutations to clients over WebSockets. Authorise with API key, Cognito, IAM, OIDC or Lambda, and add field-level rules with @aws_auth directives or resolver logic. Merged APIs and caching help scale, and offline-capable clients sync through Amplify libraries.
Real World Example
A streaming platform captures playback events from millions of devices in a KDS stream keyed by deviceId. A Lambda consumer updates real-time dashboards, an enhanced fan-out consumer feeds fraud detection with low latency, and Firehose archives everything to S3 in Parquet for Athena. A skewed key (a few huge accounts) created a hot shard, fixed by appending a bounded random suffix to the partition key. The mobile app uses AppSync subscriptions to push live "now watching" counts.
Architecture Diagram
Records are partitioned across shards and read independently by several consumers.
- 1Producers send records with a partition key.
- 2Kinesis hashes the key to pick a shard and stores the record in order.
- 3Each consumer reads from its own position independently.
- 4Firehose batches the same data into S3 for analytics.
Best Practices
- ✓Choose high-cardinality partition keys to avoid hot shards.
- ✓Use PutRecords with retry of failed records, or the KPL.
- ✓Monitor IteratorAgeMilliseconds and scale shards or parallelization.
- ✓Use enhanced fan-out when several consumers need full throughput.
- ✓Use AppSync where clients need flexible queries and real-time subscriptions.
Common Interview Questions
Exam Tips
DVA-C02 focus
- 1 MB/s or 1,000 records/s per shard for writes; 2 MB/s reads.
- Multiple consumers needing their own throughput -> enhanced fan-out.
- Deliver streaming data to S3/Redshift with minimal code -> Firehose.
- Flexible mobile queries and real-time updates -> AppSync.
Chapter quiz
Messaging and Integration · 10 questions
1.Messages in an SQS standard queue are sometimes processed twice because a task takes about 2 minutes while the queue uses the default settings. What is the best fix?
2.An order event must reach billing, shipping and analytics systems independently, with each system able to fall behind without losing messages. Which design fits?
3.A workflow must wait up to several days for a manager's approval before continuing. Which solution is most appropriate?
4.A Kinesis producer receives ProvisionedThroughputExceededException even though overall stream traffic is low. Most records share the same partition key. What is the likely issue and fix?
5.A team wants to react when a CodePipeline execution fails and route the event to a Lambda function without polling. What should they use?
6.Only the billing service should receive SNS messages whose attribute eventType equals 'invoice'. How do you do this without code changes in the publisher?
7.Orders for the same customer must be processed in order, with no duplicates. Which queue is right?
8.A workflow needs human approval that may take days, plus retries and parallel branches. Which service fits?
9.Several Lambda functions consume the same Kinesis shard and one slow consumer delays others. What improves this?
10.A mobile client needs real-time updates to a GraphQL query result when data changes. What should be used?
0 of 10 answered
Finished this lesson?
0 of 46 lessons done · 0% of the course

