Lesson 6 of 6 CloudWatch Logs and Log Analytics

Analysing Real-Time Log Streams and Log Archives

Different questions need different analysis tools: detecting an attack pattern within seconds needs stream processing, while investigating six months of access patterns needs SQL over an archive. This lesson explains Amazon Kinesis Data Streams and Amazon Managed Service for Apache Flink for real-time log analysis, and Amazon Athena for querying logs in S3, including partitioning and partition projection, with OpenSearch Service as a complementary option.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe Kinesis Data Streams capacity, retention and consumer options for real-time log processing.
  • Explain how Managed Service for Apache Flink and Lambda analyse log streams in real time.
  • Explain how Athena queries CloudTrail, ALB and VPC Flow Logs in S3, and how partitioning and partition projection reduce cost.
  • Choose an analysis approach for a log analysis requirement.

Kinesis Data Streams for Logs

Amazon Kinesis Data Streams ingests records into shards. In provisioned mode, each shard accepts up to 1 MB or 1,000 records per second of writes and supports 2 MB per second of reads shared among standard consumers; in on-demand mode, capacity scales automatically. Records are ordered within a shard by partition key and retained for 24 hours by default, extendable to 365 days, so consumers can replay data after a failure or when a new consumer is added. Enhanced fan-out gives each registered consumer its own 2 MB per second per shard throughput with push delivery, so several real-time consumers do not compete.

Logs reach Kinesis from CloudWatch Logs subscription filters, from the Kinesis Agent or Fluent Bit on servers, and from applications using the SDK. A common monitoring metric is GetRecords.IteratorAgeMilliseconds (or Lambda's IteratorAge), which shows how far consumers have fallen behind, and WriteProvisionedThroughputExceeded, which shows producer throttling that calls for more shards or on-demand mode.

Fill in the value

Kinesis shard limits

Exam skills 4.2.4

Recall Kinesis Data Streams shard limits.

Log in to try this activity Interactive activities are free with an account.

Real-Time Analysis

Two consumer types analyse log streams in real time. AWS Lambda consumes batches per shard and suits stateless processing: filtering, enrichment, forwarding and simple threshold detection, such as flagging a specific error. Amazon Managed Service for Apache Flink runs Apache Flink applications, written in Java, Python or SQL through Studio notebooks, that perform stateful analysis over time windows: counting failed logins per user over a sliding five-minute window, joining streams, detecting anomalies with the random cut forest algorithm or computing running percentiles. Results go to another stream, Firehose, a database or an alerting path such as SNS through Lambda.

NeedTool
Forward or transform each recordLambda or Firehose transformation
Stateful windows, aggregations, joins, anomaly scoringManaged Service for Apache Flink
Simple delivery to S3, OpenSearch or a partnerData Firehose
Several independent real-time consumers with replayKinesis Data Streams with enhanced fan-out

The following diagram shows the consumers of a log stream and what each suits.

Consumers for real-time log analysis. A Kinesis data stream receives log records, for example from a subscription filter. Lambda consumes batches per shard for stateless work: filtering, enrichment, forwarding and simple threshold checks. Managed Service for Apache Flink performs stateful analysis over time windows, such as counting failed logins per user in a sliding five-minute window, joining streams and scoring anomalies. Firehose delivers records to S3, OpenSearch or a partner, and enhanced fan-out serves several independent consumers.
Stateless work suits Lambda; windows and joins need Flink.

Querying Log Archives with Amazon Athena

Amazon Athena runs standard SQL directly against data in S3, with no infrastructure, charging per terabyte scanned. To query logs, a table is defined over the log location with a SerDe that understands the log format; AWS documents ready-made table definitions for CloudTrail, ALB, CloudFront, VPC Flow Logs, S3 server access logs and WAF logs. The CloudTrail console can create the Athena table for a trail directly.

Because Athena charges by data scanned, table design determines cost. Partitioning by account, Region and date lets queries read only the relevant prefixes when they filter on those columns. Logs from services arrive continuously under new date prefixes, so partitions would normally need to be added regularly; partition projection instead calculates partitions from configuration in the table properties, such as a date range and format, so no partition maintenance is needed and query planning is faster. Converting logs to a columnar format such as Parquet, for example in Firehose, and compressing them reduce data scanned further.

-- Who deleted security groups in the last 7 days, across all accounts?
SELECT eventtime, useridentity.arn, recipientaccountid, awsregion,
       json_extract_scalar(requestparameters, '$.groupId') AS group_id
FROM cloudtrail_logs
WHERE eventname = 'DeleteSecurityGroup'
  AND timestamp >= date_format(current_date - interval '7' day, '%Y/%m/%d')
ORDER BY eventtime DESC;

-- Top client IPs receiving 5xx responses from an ALB yesterday
SELECT client_ip, count(*) AS errors
FROM alb_logs
WHERE day = date_format(current_date - interval '1' day, '%Y/%m/%d')
  AND elb_status_code BETWEEN 500 AND 599
GROUP BY client_ip ORDER BY errors DESC LIMIT 20;

Athena query results can feed Amazon Quick Sight dashboards, and queries can be scheduled with EventBridge Scheduler and Step Functions for recurring reports. For CloudTrail, CloudTrail Lake offered a managed SQL store of events but is closed to new customers, so Athena over the trail's S3 bucket is the general approach.

Choosing an Analysis Approach

The tools in this module answer different questions, summarised below.

Kinesis with Flink or Lambda
LatencySeconds
Data windowStreaming windows
Typical questionIs an attack happening now?
Choose when Real-time detection and response.
Logs Insights
LatencyInteractive
Data windowLogs in CloudWatch
Typical questionWhat happened in this incident?
Choose when Investigation of recent logs.
Athena
LatencySeconds to minutes per query
Data windowAny history in S3
Typical questionWhat happened over months?
Choose when Cost-efficient historical and cross-account analysis.
OpenSearch Service
LatencyNear real time
Data windowIndexed retention
Typical questionSearch and explore logs interactively
Choose when Full-text search and dashboards over large log volumes.

Amazon EMR is a further option for very large log archives that need complex processing beyond SQL queries, such as sessionising billions of clickstream events or joining logs with other datasets in Apache Spark jobs. It reads the same S3 data as Athena, but it requires defining and running clusters, or EMR Serverless applications, and writing jobs. For the log questions a DevOps engineer usually faces, Athena answers with far less effort, so EMR is chosen only when the processing itself, not the query, is the requirement.

Sort into groups

Choose the analysis tool

Exam skills 4.2.4 · 4.2.5

Choose the log analysis tool for each question.

Log in to try this activity Interactive activities are free with an account.
Worked example

Detecting Credential Stuffing in Real Time

An application's authentication logs are in CloudWatch Logs. Security wants to detect when any IP address fails more than 50 logins in five minutes, block it within a minute, and investigate historical patterns over the past year.

  1. Stream

    A subscription filter sends authentication events to a Kinesis data stream in on-demand mode.

  2. Detect

    A Managed Service for Apache Flink application counts failures per source IP in a five-minute sliding window and writes IPs over the threshold to an output stream.

  3. Respond

    A Lambda function consuming the output stream adds the IP to an AWS WAF IP set and notifies the security team.

  4. History

    Firehose also archives the stream to S3 in Parquet, partitioned by date, and analysts query it with Athena using partition projection.

Check yourself

Athena queries over CloudTrail logs scan the entire bucket even when filtered to one day. What should be changed?

Show answer

Define the table with partitions (account, Region, date) and preferably partition projection, and filter on the partition columns, so Athena reads only the matching prefixes.

Exam Tips

Remember for the exam

  • Kinesis Data Streams: shards (1 MB/s or 1,000 records/s writes each), on-demand mode, 24-hour to 365-day retention, enhanced fan-out for multiple consumers; watch IteratorAge.
  • Use Managed Service for Apache Flink for stateful, windowed real-time analysis; Lambda for stateless processing.
  • Athena queries logs in S3 with SQL; partitioning and partition projection reduce data scanned; Parquet and compression reduce cost further.
  • CloudTrail Lake is closed to new customers; use Athena over the trail's S3 data.