Skip to main content

Building an AWS Analytics Stack

Build an AWS analytics stack: load data into Redshift, process big data with EMR Spark and Spot task nodes, and publish QuickSight dashboards.

Overview and What You Will Learn

An AWS analytics stack separates analysis from your production database. Amazon Redshift stores and queries large datasets in a columnar data warehouse, Amazon EMR runs Spark and Hadoop jobs to transform big data, and Amazon Quick Sight (formerly QuickSight) turns the results into interactive dashboards. Together they move heavy reads off your transactional systems and give business teams answers without engineering tickets.

In this guide you will learn:

  • Why OLTP and OLAP databases are different, and why analytics should not run on production
  • How Redshift columnar storage, distribution, and sort keys make analytical queries fast
  • How Redshift Serverless compares with provisioned clusters
  • Why COPY beats INSERT, and when Redshift Spectrum queries S3 in place
  • How EMR primary, core, and task nodes differ, and how Spot task nodes cut cost
  • How transient EMR clusters pay only for job time
  • How Quick Sight uses SPICE, and how row-level and column-level security control access
  • How to build the whole pipeline end to end: raw data in S3, an EMR Spark job, a Redshift load, and a dashboard

Why This Matters in Production

A food-delivery company like Swiggy produces millions of order, delivery, and interaction events a day. A GROUP BY across 500 million rows on the production RDS database competes with live order writes and slows every user. A payments company like Razorpay needs billions of transactions aggregated into daily summary tables, which is a distributed Spark job, not a SQL query on a single instance. A streaming platform like Hotstar needs content performance dashboards that analysts build themselves. Redshift, EMR, and Quick Sight are the layers that make this possible without touching production.

Core Principles

How the Pieces Fit Together

Raw data lands in S3, EMR transforms it, Redshift serves fast SQL, and Quick Sight visualises it. Each service does one job, and S3 is the shared storage between them.

flowchart TD SRC[(Production RDS
and event streams)] -->|Export| S3[(S3 data lake)] S3 -->|Spark jobs| EMR[EMR cluster] EMR -->|Curated Parquet| S3C[(S3 curated)] S3C -->|COPY| RS[Redshift] S3 -.->|Spectrum| RS RS -->|SPICE or direct| QS([Quick Sight dashboards]) classDef src fill:#475569,color:#ffffff classDef store fill:#F97316,color:#ffffff classDef proc fill:#8B5CF6,color:#ffffff classDef wh fill:#326CE5,color:#ffffff classDef bi fill:#10B981,color:#ffffff class SRC src class S3,S3C store class EMR proc class RS wh class QS bi
Why Analytics Needs a Separate Database

OLTP databases handle many small reads and writes with strong integrity, and OLAP databases handle a few large queries that scan and aggregate millions of rows. Running one workload on the other's engine hurts both.

Aspect OLTP (RDS, Aurora, DynamoDB) OLAP (Redshift)
Typical query Insert or update one order Sum revenue by city for a year
Storage layout Row-based Column-based
Optimised for Fast writes, integrity Fast scans, aggregation

A full scan for SELECT city, COUNT(*), SUM(amount) FROM orders GROUP BY city on a production table with 500 million rows takes minutes and slows live writes while it runs. The fix is to copy data to a separate analytical store and query it there. Zero-ETL integrations can replicate supported sources such as Aurora into Redshift without a pipeline you maintain.

How Redshift Stores and Queries Data

Redshift stores each column separately, so a query reads only the columns it needs. For SELECT SUM(amount) FROM orders, a row store must read every column of every row, while Redshift reads just the amount column. Per-column compression and sorted blocks reduce the data scanned further.

◈ DIAGRAM
Row store: Rahul | Mumbai | 450 | 2026-09-15 | delivered (reads all five columns)
Column store: [amount: 450, 120, 890, ...] (reads one column)

A Redshift cluster has a leader node that receives SQL, plans the query, and returns results, plus compute nodes that store data and run query fragments in parallel across slices. More parallelism means faster scans. Modern RA3 nodes keep data in managed storage, so you can scale compute and storage independently.

Two table design choices matter most:

  • Sort key: orders data on disk, usually by a date or timestamp, so range filters skip blocks
  • Distribution style: decides which node holds each row, and should keep large joins local, with AUTO as a sensible default
Redshift Serverless vs Provisioned Clusters

Choose Serverless for variable or unknown workloads and provisioned clusters for steady, predictable ones.

Aspect Serverless Provisioned
Capacity Scales automatically in RPUs You choose node type and count
Billing Compute used per second, plus storage Per node-hour, even when idle
Best for Intermittent, dev and test, spiky BI Continuous heavy workloads with reserved pricing

With Serverless you set a base capacity and a maximum RPU limit, which caps spend.

Why COPY Beats INSERT for Loading Data

Use COPY to bulk load from S3, because each compute node loads its own slice of the files in parallel. Single-row INSERT statements send one round trip per row, which is acceptable for a few thousand rows and takes hours for millions. Use Parquet or compressed files, and split large loads into many files so every slice has work.

SQL
COPY orders
FROM 's3://devops-analytics/orders/2026/09/'
IAM_ROLE 'arn:aws:iam::123456789012:role/RedshiftS3Role'
FORMAT AS PARQUET;
When to Use Redshift Spectrum

Spectrum lets Redshift query files in S3 through external tables, without loading them. Use it for cold or rarely queried data, or to join warehouse tables with data in your lake. It is billed by data scanned, at about $5 per TB at the time of writing, so partition and use columnar formats to reduce cost.

SQL
CREATE EXTERNAL SCHEMA spectrum_schema
FROM DATA CATALOG
DATABASE 'devops_analytics'
IAM_ROLE 'arn:aws:iam::123456789012:role/RedshiftSpectrumRole'
CREATE EXTERNAL DATABASE IF NOT EXISTS;
SELECT city, COUNT(*) AS orders
FROM spectrum_schema.orders
WHERE year = '2026' AND month = '09'
GROUP BY city;
What EMR Does

Amazon EMR runs open-source big data frameworks such as Spark, Hadoop, Hive, and Presto without you building and patching a cluster. You choose a framework, instance types, and a job, and EMR provisions and manages the rest. You can run EMR on EC2 clusters, on EKS, or as EMR Serverless, which removes cluster sizing entirely.

EMR Node Types and Spot Instances

An EMR cluster has three node roles, and the role decides what is safe to run on Spot.

flowchart TD P[Primary node
On-Demand] --> C1[Core node
tasks and HDFS] P --> C2[Core node
tasks and HDFS] P --> T1[Task node
Spot, tasks only] P --> T2[Task node
Spot, tasks only] classDef primary fill:#EF4444,color:#ffffff classDef core fill:#326CE5,color:#ffffff classDef task fill:#10B981,color:#ffffff class P primary class C1,C2 core class T1,T2 task
  • Primary node (formerly master): coordinates the cluster and tracks jobs. Losing it ends the cluster, so keep it On-Demand. A multi-primary option exists for high availability.
  • Core nodes: run tasks and store HDFS data. Removing them risks data loss, so use On-Demand or a stable mix.
  • Task nodes: run tasks only, with no HDFS data. They can be added or removed freely, so they are the right place for Spot Instances, which can be discounted by up to 90 percent compared with On-Demand.

If a Spot task node is reclaimed, Spark reschedules its work on the remaining nodes and no data is lost. Use instance fleets with several instance types to improve Spot availability.

The Transient Cluster Pattern

Store input and output in S3 instead of HDFS, start a cluster when a job arrives, and let it terminate when the job finishes. You pay only for the minutes the cluster runs, and the data remains in S3. This is the most cost-effective pattern for batch analytics.

What Quick Sight Does

Amazon Quick Sight is AWS's serverless business intelligence service, now part of Amazon Quick Suite. Analysts build charts and dashboards from sources such as Redshift, Athena, S3, RDS, and Aurora without managing BI servers. Sign-ups use the Enterprise edition, while the author-only Standard edition remains available through the CreateAccountSubscription API for small teams.

  • SPICE is Quick Sight's in-memory engine. Importing data into SPICE means dashboard interactions query memory instead of Redshift, so they respond quickly and Redshift is not hit on every click. Each author includes 10 GB of SPICE, and extra capacity is billed per GB. Schedule refreshes so data stays current.
  • Direct query skips SPICE and runs against the source each time, which suits data that must be fresh at every view.
  • Column-level security (CLS) hides chosen columns from chosen users, so Finance sees margin while Sales sees the same dataset without it.
  • Row-level security (RLS) filters rows by user, so a Mumbai regional manager sees only Mumbai data in the same dashboard.

Detailed Step-by-Step Practical Lab

You will generate 200,000 orders, load them into Redshift Serverless with COPY, aggregate them with an EMR Spark job on Spot task nodes, load the summary, and build a dashboard. You need Terraform 1.6 or later, the AWS CLI, Python 3.12 with pandas and pyarrow, and an account with a default VPC. EMR and Redshift incur small charges while they run, so clean up promptly.

Step 1: Create the Infrastructure with Terraform
HCL
terraform {
required_version = ">= 1.6.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
}
provider "aws" {
region = "ap-south-1"
}
data "aws_caller_identity" "current" {}
data "aws_vpc" "default" {
default = true
}
data "aws_subnets" "default" {
filter {
name = "vpc-id"
values = [data.aws_vpc.default.id]
}
}
# Shared storage for raw data, EMR logs, jobs, and results
resource "aws_s3_bucket" "lake" {
bucket = "devops-analytics-lab-${data.aws_caller_identity.current.account_id}"
force_destroy = true
}
# Role that Redshift assumes to read from S3 during COPY
data "aws_iam_policy_document" "redshift_assume" {
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["redshift.amazonaws.com"]
}
}
}
resource "aws_iam_role" "redshift" {
name = "devops-redshift-s3-role"
assume_role_policy = data.aws_iam_policy_document.redshift_assume.json
}
data "aws_iam_policy_document" "redshift_s3" {
statement {
actions = ["s3:GetObject", "s3:ListBucket"]
resources = [
aws_s3_bucket.lake.arn,
"${aws_s3_bucket.lake.arn}/*",
]
}
}
resource "aws_iam_role_policy" "redshift_s3" {
name = "read-lake-bucket"
role = aws_iam_role.redshift.id
policy = data.aws_iam_policy_document.redshift_s3.json
}
resource "aws_security_group" "redshift" {
name = "devops-redshift-sg"
description = "Redshift Serverless workgroup"
vpc_id = data.aws_vpc.default.id
# No inbound rules: this lab uses the Data API. Quick Sight access is added later.
}
resource "aws_redshiftserverless_namespace" "main" {
namespace_name = "devops-namespace"
db_name = "dev"
admin_username = "admin"
manage_admin_password = true # password is stored in Secrets Manager
iam_roles = [aws_iam_role.redshift.arn]
}
resource "aws_redshiftserverless_workgroup" "main" {
namespace_name = aws_redshiftserverless_namespace.main.namespace_name
workgroup_name = "devops-workgroup"
base_capacity = 8 # RPUs available at minimum
max_capacity = 32 # hard cap on spend
publicly_accessible = false
subnet_ids = data.aws_subnets.default.ids
security_group_ids = [aws_security_group.redshift.id]
}
output "lake_bucket" {
value = aws_s3_bucket.lake.id
}
output "redshift_role_arn" {
value = aws_iam_role.redshift.arn
}
Bash
terraform init
terraform apply
Step 2: Generate and Upload Sample Orders

Save as make_orders.py. Python date objects are written as Parquet dates, which load into a Redshift DATE column.

Python
import random
from datetime import date, timedelta
import pandas as pd
random.seed(7)
cities = ["Mumbai", "Pune", "Bangalore", "Chennai", "Delhi"]
statuses = ["delivered", "delivered", "delivered", "pending", "cancelled"]
start = date(2026, 9, 1)
rows = []
for i in range(200_000):
rows.append(
dict(
order_id=f"ORD-{i:06d}",
user_id=f"user-{random.randint(1, 5000):04d}",
amount=random.randint(60, 2500),
city=random.choice(cities),
status=random.choice(statuses),
order_date=start + timedelta(days=random.randint(0, 29)),
)
)
pd.DataFrame(rows).to_parquet("orders.parquet", index=False)
print("Wrote", len(rows), "orders")
Bash
python3 make_orders.py
BUCKET=$(terraform output -raw lake_bucket)
aws s3 cp orders.parquet "s3://$BUCKET/orders/orders.parquet"
Step 3: Load Data into Redshift with COPY

The Redshift Data API runs SQL without a driver or open network port. This helper submits a statement and waits for it.

Bash
rs() {
local id state
id=$(aws redshift-data execute-statement \
--workgroup-name devops-workgroup --database dev \
--sql "$1" --query Id --output text)
until state=$(aws redshift-data describe-statement --id "$id" \
--query Status --output text) && [[ "$state" =~ ^(FINISHED|FAILED|ABORTED)$ ]]; do
sleep 2
done
echo "Status: $state"
aws redshift-data describe-statement --id "$id" --query Error --output text
aws redshift-data get-statement-result --id "$id" --query Records --output text 2>/dev/null || true
}
ROLE_ARN=$(terraform output -raw redshift_role_arn)
rs "CREATE TABLE orders (
order_id VARCHAR(20),
user_id VARCHAR(20),
amount BIGINT,
city VARCHAR(50),
status VARCHAR(20),
order_date DATE
) DISTSTYLE AUTO SORTKEY (order_date)"
# Column order in the table must match the Parquet file
rs "COPY orders FROM 's3://$BUCKET/orders/' IAM_ROLE '$ROLE_ARN' FORMAT AS PARQUET"
rs "SELECT COUNT(*) FROM orders"
# Expected: 200000
rs "SELECT city, COUNT(*) AS orders, SUM(amount) AS revenue
FROM orders WHERE status = 'delivered'
GROUP BY city ORDER BY revenue DESC"

If a load fails, query SYS_LOAD_ERROR_DETAIL to see the file, column, and reason.

Step 4: Run an EMR Spark Job on a Transient Cluster

Save as daily_summary.py. It reads raw orders from S3, aggregates delivered orders per day and city, and writes Parquet back to S3.

Python
import sys
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
source, target = sys.argv[1], sys.argv[2]
spark = SparkSession.builder.appName("daily-order-summary").getOrCreate()
orders = spark.read.parquet(source)
summary = (
orders.filter(F.col("status") == "delivered")
.groupBy("order_date", "city")
.agg(F.count("*").alias("orders"), F.sum("amount").alias("revenue"))
)
summary.write.mode("overwrite").parquet(target)
print(f"Wrote {summary.count()} summary rows")
spark.stop()

Start a cluster with one On-Demand primary, two On-Demand core nodes, and two Spot task nodes. --auto-terminate shuts it down when the step ends, and TERMINATE_CLUSTER stops it if the step fails.

Bash
aws s3 cp daily_summary.py "s3://$BUCKET/jobs/daily_summary.py"
aws emr create-default-roles
# Pick the newest 7.x release label available in this Region
LABEL=$(aws emr list-release-labels --query 'ReleaseLabels' --output text \
| tr '\t' '\n' | grep '^emr-7' | sort -V | tail -1)
aws emr create-cluster \
--name devops-daily-summary \
--release-label "$LABEL" \
--applications Name=Spark \
--use-default-roles \
--instance-groups \
InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m5.xlarge \
InstanceGroupType=CORE,InstanceCount=2,InstanceType=m5.xlarge \
InstanceGroupType=TASK,InstanceCount=2,InstanceType=m5.xlarge,Market=SPOT \
--log-uri "s3://$BUCKET/emr-logs/" \
--steps "Type=Spark,Name=daily-summary,ActionOnFailure=TERMINATE_CLUSTER,Args=[--deploy-mode,cluster,s3://$BUCKET/jobs/daily_summary.py,s3://$BUCKET/orders/,s3://$BUCKET/summary/]" \
--auto-terminate \
--region ap-south-1
# Note the ClusterId (j-XXXXXXXXXXXX) in the output
aws emr describe-cluster --cluster-id j-XXXXXXXXXXXX \
--query 'Cluster.Status.State' --output text
# STARTING, RUNNING, TERMINATING, then TERMINATED

If the cluster fails to start because Spot capacity or the Spot vCPU quota is unavailable, rerun with the task group set to On-Demand, and use instance fleets with several instance types in production.

Step 5: Load the Summary into Redshift
Bash
aws s3 ls "s3://$BUCKET/summary/"
rs "CREATE TABLE daily_summary (
order_date DATE,
city VARCHAR(50),
orders BIGINT,
revenue BIGINT
)"
rs "COPY daily_summary FROM 's3://$BUCKET/summary/' IAM_ROLE '$ROLE_ARN' FORMAT AS PARQUET"
rs "SELECT order_date, SUM(revenue) FROM daily_summary
GROUP BY order_date ORDER BY order_date LIMIT 5"

Parquet part files are loaded and the _SUCCESS marker is ignored. The summary table is tiny compared with orders, which is why dashboards usually point at curated tables like this.

Step 6: Connect Quick Sight and Build a Dashboard

The workgroup is private, so Quick Sight needs a network path to it.

  1. Sign in to Amazon Quick Sight in ap-south-1, create an account, and note your Quick Sight user name.
  2. Under Manage Quick Sight, open VPC connections and add one for the default VPC using subnets in the same VPC and a security group you create for Quick Sight.
  3. Add an inbound rule to devops-redshift-sg that allows TCP 5439 from the Quick Sight security group.
  4. Create a dataset from Redshift, choose the VPC connection, enter the workgroup endpoint, database dev, and a database user, then select daily_summary.
  5. Choose Import to SPICE, then build a bar chart of SUM(revenue) by city and a line chart of revenue by order_date.
  6. Schedule a SPICE refresh so the data stays current, then publish and share the dashboard.
Step 7: Add Row-Level and Column-Level Security

For row-level security, create a rules file where UserName matches each Quick Sight user and the other columns filter the dataset. A blank value means all rows.

TEXT
UserName,city
arjun,Mumbai
priya,Bangalore

Upload it as a dataset, then open daily_summary, choose Row-level security, and select the rules dataset. For column-level security, open the dataset's column-level security setting, pick the columns to protect such as revenue, and grant access only to the users or groups that may see them. Sign in as a restricted user to confirm the dashboard now shows only permitted rows and columns.

Step 8: Clean Up
Bash
# Delete the Quick Sight dataset and VPC connection in the console first
terraform destroy

Confirm no EMR cluster is still active.

Bash
aws emr list-clusters --active --query 'Clusters[].Id' --output text

Production Best Practices & Common Pitfalls

Common Mistake

Running analytical GROUP BY queries on the production RDS database. A scan across hundreds of millions of rows competes for I/O with live traffic and slows every user. Move data to Redshift with COPY, zero-ETL, or a pipeline, and query it there.

Common Mistake

Loading millions of rows with INSERT. Each statement is a separate round trip, so the load takes hours. Use COPY from S3 with Parquet or compressed files split across many objects.

Tip

Run batch analytics on transient EMR clusters that read from and write to S3, with Spot task nodes. You pay only while the job runs, and Spot can cut task-node compute cost substantially, though savings vary with market conditions.

Remember

Keep the EMR primary node and core nodes On-Demand, and put only task nodes on Spot. Core nodes hold HDFS data, and losing the primary node ends the cluster.

Security

Give Redshift roles read access only to the buckets they load from, keep workgroups private, store admin credentials in Secrets Manager, and enforce row-level and column-level security in Quick Sight instead of building separate datasets per team.

  • Design tables for your queries. Sort on the column you filter by most, usually a date, and let distribution default to AUTO unless a large join proves otherwise.
  • Cap Serverless spend. Set a maximum RPU limit and usage limits so a runaway query cannot surprise you.
  • Use materialized views for repeated aggregates. Precomputing dashboard queries is cheaper than recomputing them on every refresh.
  • Prefer Parquet end to end. It makes COPY, Spark, and Spectrum faster and cheaper because they read only needed columns.
  • Avoid storing the only copy in HDFS. Cluster-local storage disappears when a transient cluster terminates, so write results to S3.
  • Consider EMR Serverless for simple jobs. It removes cluster sizing and idle time when you do not need node-level control.
  • Refresh SPICE on a schedule. Match refresh frequency to how fresh dashboards must be, and use incremental refresh for large datasets.

Quick Reference & Troubleshooting Commands

Command Description
aws redshift-serverless list-workgroups List Serverless workgroups
aws redshift-data execute-statement Run SQL through the Data API
aws redshift-data describe-statement --id ID Check a statement's status and error
aws emr list-clusters --active List running EMR clusters
aws emr describe-cluster --cluster-id ID Show cluster state and settings
aws emr list-steps --cluster-id ID Show step status
aws emr terminate-clusters --cluster-ids ID Stop a cluster
aws quicksight list-data-sets --aws-account-id ACCOUNT List Quick Sight datasets
Problem Likely fix
COPY fails Query SYS_LOAD_ERROR_DETAIL, and check column order, types, and role access
Queries are slow Review sort and distribution keys, and check for skewed data
EMR cluster ends with errors Read the step logs under the --log-uri path in S3
Spot nodes unavailable Use instance fleets with several types, or fall back to On-Demand
Quick Sight cannot reach Redshift Check the VPC connection, subnets, and the inbound rule on port 5439
SPICE refresh fails Open the ingestion error details and check source permissions and data types
Dashboard shows stale data Increase refresh frequency or switch the dataset to direct query

Resources

AWS Direct Connect vs VPN: Run Both as Failover

AWS Direct Connect vs VPN: Run Both as Failover

Run AWS Direct Connect as primary and Site-to-Site VPN as BGP failover. Size the backup, set route preference and test it before an outage does.

10 min read•Aug 2026
Lambda vs Fargate vs EC2 Spot: The Cost Crossover

Lambda vs Fargate vs EC2 Spot: The Cost Crossover

Lambda vs Fargate vs EC2 Spot, at the crossover where Lambda stops being cheaper — 2026 pricing, invocation thresholds, and interruption math.

5 min read•Aug 2026
Secrets Manager vs Parameter Store vs Vault

Secrets Manager vs Parameter Store vs Vault

Secrets Manager vs Parameter Store vs Vault: cost math, rotation, dynamic secrets and a decision flow, plus the Vault, IBM and OpenBao licensing context.

10 min read•Aug 2026
AWS VPC Security: Hardening Every Layer

AWS VPC Security: Hardening Every Layer

Harden your AWS VPC in layers: subnets, Security Groups, NACLs, Flow Logs, endpoints, and IAM conditions, with CLI examples for production.

10 min read•Jul 2026
Event-Driven Architecture on AWS Explained

Event-Driven Architecture on AWS Explained

Build event-driven systems on AWS with SQS, SNS, EventBridge and Kinesis: fan-out, DLQs, idempotent consumers and queue-based scaling.

11 min read•Jul 2026
S3 vs RDS vs DynamoDB: Choosing AWS Storage

S3 vs RDS vs DynamoDB: Choosing AWS Storage

Choosing S3, RDS, or DynamoDB wrong costs you in performance, cost, and scalability. Here is a practical decision guide based on your actual access patterns.

5 min read•Jul 2026
AWS Cost Optimisation: 8 Actions That Cut Bills

AWS Cost Optimisation: 8 Actions That Cut Bills

Cut your AWS bill without re-architecting: eight ordered steps from anomaly alerts and tagging to rightsizing, VPC endpoints, Savings Plans and Spot.

11 min read•Jul 2026
EC2 vs Lambda vs Fargate: Choosing AWS Compute

EC2 vs Lambda vs Fargate: Choosing AWS Compute

Choose between EC2, Lambda and Fargate using traffic shape, state and runtime limits, with worked cost break-evens instead of rules of thumb.

11 min read•Jul 2026

Explore More in AWS Messaging, Analytics, and Containers

All 6 Topics

Frequently Asked Questions

Is Building an AWS Analytics Stack free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Building an AWS Analytics Stack topic cover?

Build an AWS analytics stack: load data into Redshift, process big data with EMR Spark and Spot task nodes, and publish QuickSight dashboards.

Found a mistake, an outdated step or a broken link?