AWS Data Engineering
Building a Fully Automated Spotify ETL Data Pipeline on AWS
💡A serverless pipeline that extracts Spotify playlist data, transforms it with AWS Lambda, stores clean datasets in S3, and enables…
💡A serverless pipeline that extracts Spotify playlist data, transforms it with AWS Lambda, stores clean datasets in S3, and enables instant querying with AWS Glue & Athena.
🟩 Introduction
In modern data engineering, building automated ETL pipelines using serverless tools is no longer a “nice to have” — it’s becoming the default. Serverless means zero infrastructure management, auto-scaling, and pay-only-for-usage.
In this walkthrough, we’ll build a fully automated Spotify ETL pipeline on AWS that:
🔹 Extracts playlist data from the Spotify API
🔹 Loads raw JSON into S3
🔹 Automatically triggers a transformation Lambda
🔹 Cleans & normalizes album, artist, and song data
🔹 Stores each dataset in structured CSV form
🔹 Makes the data instantly queryable via AWS Glue & Athena
🔹 Runs on a schedule (every minute or daily) with zero human intervention
This is the exact pipeline design used by many modern DE teams — lightweight, cost-efficient, and fully serverless.
📝 TL;DR
This project builds a fully automated, serverless Spotify ETL pipeline on AWS.
It extracts playlist data using the Spotify API, stores raw JSON in S3, automatically triggers a transformation Lambda to clean and normalize album/artist/song datasets, writes structured CSV files into S3, and makes them instantly queryable using AWS Glue + Athena.
The entire pipeline is scheduled, event-driven, scalable, and requires zero servers, making it production-ready and cost-efficient.
🏗️ What You Will Build
By the end of this walkthrough, you’ll have a fully automated Spotify ETL data pipeline powered entirely by AWS serverless services. You’ll build:
- A Lambda Extractor that authenticates with Spotify, fetches playlist data via API, and stores raw JSON files in S3.
- A Transformation Lambda that is triggered automatically on new files, cleans the data, flattens nested JSON, and produces structured CSV datasets for:
songs_dataalbum_dataartist_data- A Medallion-style S3 Data Lake with clear separation between Raw → Processed → Transformed zones.
- Automated Orchestration using EventBridge rules and S3 triggers.
- Data Cataloging using AWS Glue Crawlers to infer schemas from transformed CSVs.
- Interactive SQL analytics powered by Amazon Athena to query song popularity, artist trends, album metadata, and more.
This project mirrors how modern data teams design real-world, serverless ETL systems.
🧱 Spotify ETL Pipeline Architecture Overview

A fully serverless ETL architecture where a scheduled CloudWatch trigger runs the Extraction Lambda to pull Spotify playlist data via API, land raw JSON into S3 (bronze layer), automatically invoke a Transformation Lambda through an S3 ObjectCreated event to normalize Songs, Albums, and Artists (silver layer), store cleaned CSVs in S3, and then use AWS Glue Crawlers and Athena to create a queryable analytics layer (gold).
Architecture Components:
- Spotify API → Lambda Extractor (Spotipy + boto3)
- Raw Zone (S3):
raw_data/to_processed/ - Trigger: S3 Event (ObjectCreated)
- Lambda Transformer: Normalizes Song / Artist / Album
- Transformed Zone (S3):
transformed_data/songs_datatransformed_data/album_datatransformed_data/artist_data- Processed Zone: Moves consumed JSON →
raw_data/processed/ - AWS Glue Crawler
- Amazon Athena Query Layer
This follows a Bronze → Silver → Gold medallion architecture in serverless form.
🧱 Why Spotify? Why Serverless?
Spotify’s playlist API is a perfect demo because it provides nested JSON structures — ideal for ETL learning:
- Nested
albummetadata - Multiple artists per track
- Song-level popularity & duration
- Added timestamps
AWS gives us the perfect serverless stack to automate this:

Above table summarizes each layer of the automated Spotify ETL pipeline and the AWS service powering it.
This is how real-world DE teams design pipelines.
💰 How Much Does This Pipeline Actually Cost?
In my real AWS bill, running this full Spotify ETL pipeline one time cost:
AWS Glue Crawler: $0.05
Taxes: $0.01
➡️ Total Cost per Run: $0.06 USD (~₹5 INR)
All other AWS services — Lambda, S3, EventBridge, Athena — stayed fully within free-tier usage for this pipeline.
This means the only paid component in a typical run is the Glue Crawler.
Even if you run this pipeline daily:
➡️ $0.06 × 30 = $1.80/month (~₹150/month)
This makes it one of the cheapest possible production-style ETL pipeline architectures.
⚠️Note:
In my AWS bill, all services except Glue remained fully free because Lambda, S3, EventBridge, and Athena all stayed within AWS Free Tier limits.
Only the AWS Glue Crawler incurred a charge of $0.05 + $0.01 tax, resulting in a total pipeline cost of $0.06 USD (~₹5)for a complete end-to-end run.
🟦 Step-by-Step Guide: Building the Pipeline
Below is your exact workflow, rewritten into polished DataForge style.
🟩 Step 1 — Create an S3 Bucket Structure
Create an S3 bucket, example:
spotify-etl-pipeline001Inside it, create three zones:
1️⃣ Raw Zone
raw_data/
to_processed/
processed/2️⃣ Transformed Zone
transformed_data/
songs_data/
album_data/
artist_data/This is your Bronze → Silver → Gold layout.
🟩 Step 2 — Create Spotify Extract Lambda (Extract Layer)
2.1 Create Lambda Function
Name it:
spotify_api_data_extract2.2 Add Environment Variables:
Go to Configuration → Environment Variables
client_id = <your_spotify_client_id>
client_secret = <your_spotify_client_secret>2.3 Install Spotipy via Lambda Layer
Lambda doesn’t allow pip install inside the editor.
So:
- Go to Lambda → Layers
- Create a layer called
spotipy_layer - Upload a ZIP containing Spotipy + dependencies
- Attach layer to your Lambda
2.4 Write Extract Code
import json
import os
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import boto3
from datetime import datetime
def lambda_handler(event, context):
client_id=os.environ['client_id']
client_secret=os.environ['client_secret']
client_credentials_manager = SpotifyClientCredentials(
client_id=client_id,
client_secret=client_secret
)
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
playlist_link = "https://open.spotify.com/playlist/6VOedaf3eNWDOVpa9Qdlvg"
playlist_URI = playlist_link.split("/")[-1].split("?")[0]
spotify_data = sp.playlist_tracks(playlist_URI)
client=boto3.client('s3')
filename = "spotify_raw_" + str(datetime.now()) + ".json"
client.put_object(
Bucket="spotify-etl-pipeline001",
Key="raw_data/to_processed/" + filename,
Body=json.dumps(spotify_data)
)
return {"status": "success", "file": filename}2.5 IAM Permissions
Go to:
Configuration → Permissions → Execution Role → Add Policy
Give:
✔️ AmazonS3FullAccess
✔️ Logs permissions
2.6 Increase Timeout
Go to:
Configuration → General Settings → Timeout = 1 min
🟩 Step 3 — Create the Transformation Lambda
This function:
- Reads every JSON file from
to_processed - Extracts albums, artists, and songs
- Writes them as CSV to transformed zones
- Moves processed JSON to
processed/
3.1 Create Lambda Function
Name:
spotify_transformation_load_function3.2 Add Pandas Layer
In Lambda → Layers → Add AWS Provided Pandas Layer:
AWSDataWrangler / Pandas3.3 Add Code
import json
import boto3
from datetime import datetime
from io import StringIO
import pandas as pd
def album(data):
album_list = []
for row in data['items']:
album_element = {
'album_id': row['track']['album']['id'],
'name': row['track']['album']['name'],
'release_date': row['track']['album']['release_date'],
'total_tracks': row['track']['album']['total_tracks'],
'url': row['track']['album']['external_urls']['spotify']
}
album_list.append(album_element)
return album_list
def artist(data):
artist_list = []
for row in data['items']:
for artist in row['track']['artists']:
artist_dict = {
'artist_id': artist['id'],
'artist_name': artist['name'],
'external_url': artist['href']
}
artist_list.append(artist_dict)
return artist_list
def songs(data):
song_list = []
for row in data['items']:
song_element = {
'song_id': row['track']['id'],
'song_name': row['track']['name'],
'duration_ms': row['track']['duration_ms'],
'url': row['track']['external_urls']['spotify'],
'popularity': row['track']['popularity'],
'song_added': row['added_at'],
'album_id': row['track']['album']['id'],
'artist_id': row['track']['artists'][0]['id']
}
song_list.append(song_element)
return song_list
def lambda_handler(event, context):
s3 = boto3.client('s3')
Bucket = "spotify-etl-pipeline001"
Key = "raw_data/to_processed/"
spotify_data = []
spotify_keys = []
for file in s3.list_objects(Bucket=Bucket, Prefix=Key)['Contents']:
file_key = file['Key']
if file_key.endswith(".json"):
response = s3.get_object(Bucket=Bucket, Key=file_key)
content = response['Body']
jsonObject = json.loads(content.read())
spotify_data.append(jsonObject)
spotify_keys.append(file_key)
for data in spotify_data:
album_df = pd.DataFrame(album(data)).drop_duplicates(subset=['album_id'])
artist_df = pd.DataFrame(artist(data)).drop_duplicates(subset=['artist_id'])
song_df = pd.DataFrame(songs(data))
album_df['release_date'] = pd.to_datetime(album_df['release_date'])
song_df['song_added'] = pd.to_datetime(song_df['song_added'])
# Upload songs
song_buf = StringIO()
song_df.to_csv(song_buf, index=False)
s3.put_object(
Bucket=Bucket,
Key=f"transformed_data/songs_data/songs_{datetime.now()}.csv",
Body=song_buf.getvalue()
)
# Upload albums
album_buf = StringIO()
album_df.to_csv(album_buf, index=False)
s3.put_object(
Bucket=Bucket,
Key=f"transformed_data/album_data/album_{datetime.now()}.csv",
Body=album_buf.getvalue()
)
# Upload artists
art_buf = StringIO()
artist_df.to_csv(art_buf, index=False)
s3.put_object(
Bucket=Bucket,
Key=f"transformed_data/artist_data/artist_{datetime.now()}.csv",
Body=art_buf.getvalue()
)
# Move processed JSON into processed folder
s3_resource = boto3.resource('s3')
for key in spotify_keys:
copy_source = {'Bucket': Bucket, 'Key': key}
s3_resource.meta.client.copy(copy_source, Bucket, 'raw_data/processed/' + key.split('/')[-1])
s3_resource.Object(Bucket, key).delete()
return {"status": "success", "processed_files": len(spotify_keys)}🟩 Step 4 — Automation with Triggers
4.1 Transform Lambda Trigger
Create an S3 Event Trigger:
- Event type:
s3:ObjectCreated:* - Prefix:
raw_data/to_processed/
Whenever a new raw file is uploaded → transformation runs automatically.
4.2 Automate Extraction with EventBridge
Go to EventBridge → Rule → Schedule
Example:
rate(1 minute)Or switch to daily to avoid charges:
rate(1 day)🟩 Step 5 — Load Layer: Glue & Athena
5.1 Create AWS Glue Crawler
Create 3 crawlers:
- Songs data → points to
transformed_data/songs_data/ - Album data → points to
transformed_data/album_data/ - Artist data → points to
transformed_data/artist_data/
Run crawler → Glue creates tables in the Data Catalog.
5.2 Query with Athena
Example queries:
SELECT name, sum(total_tracks)
FROM "spotify_db"."album_data"
GROUP BY name
ORDER BY sum(total_tracks) DESC;
The image shows an Athena query selecting album names and aggregating total_tracks from the album_data table. With Glue-generated schemas, Athena enables instant querying of transformed Spotify datasets stored in S3 — without provisioning any servers.
SELECT artist_name, COUNT(*) AS songs
FROM "spotify_db"."artist_data"
GROUP BY artist_name
ORDER BY songs DESC;This query identifies which artists appear most frequently across your playlist dataset - an instant analytical insight made possible through Athena + Glue + S3.
You now have a fully queryable Spotify analytics lake.
🔍 At This Stage — Your Analytics Layer Is Fully Active
Now that your ETL pipeline, Glue catalog, and Athena tables are all set up, you can run any number of analytical queries on your Spotify dataset. Athena makes it trivial to explore patterns, build dashboards, and derive insights at scale — all directly from S3.
🟧 Real-World Use Cases
This architecture mirrors real pipelines used in:
- Recommendation systems
- Music trend analysis
- Playlist personalization
- Streaming dashboards
- Artist popularity analytics
Data teams use similar serverless ETL stacks for news APIs, ecommerce logs, social media feeds, IoT data, etc.
🔧 Debugging These Failures in Practice
If you’re hitting errors like these in production — Airflow failures, Spark OOM,Kafka SSL issues — I built a tool to help.
Paste your broken code + error logs into Vayu and get back:
→ Exact root cause
→ Before/After code fix
→ Confidence score (HIGH/MEDIUM/LOW)
Free to try at vayufix.com
No signup needed for first 3 fixes.
🔥 Conclusion
This project demonstrates the real power of a serverless ETL pipeline:
- Zero servers to manage
- Fully automated
- Instant scalability
- Structured Silver/Gold datasets
- Interactive SQL querying via Athena
You’ve built an end-to-end, production-style ETL system using only:
✔️ AWS Lambda
✔️ S3
✔️ Glue
✔️ Athena
✔️ EventBridge
✔️ Spotipy
This is the type of project that stands out in a data engineering interview and portfolio.
This project was inspired by Darshil Parmar’s Spotify ETL walkthrough, and expanded with additional production elements such as cost analysis, architecture improvements, and a fully serverless medallion design.
🔥 Next in Series:
Coming Next :“Lessons Learned from Building My Data Engineering Projects”
In the next post, we’ll go beyond walkthroughs and discuss the practical lessons, pitfalls, and architecture decisions learned from building multiple real data engineering pipelines.
From handling broken APIs to designing scalable storage layers to choosing the right orchestration patterns — this next article will distill real, hard-earned engineering insights that every DE should know.
🔔 Follow for More
If you found this helpful, follow TheDataForge for your daily Spark, Databricks in Data Engineering ,Machine Learning and real-world data engineering content⚡
Let’s connect — I post daily Big Data & Spark insights at DataForgeX on X.
💬 Comment below:What feature would you add next to this Spotify ETL pipeline — a dashboard, a recommendation model, or a real-time listener analytics engine?
👉 If you found this useful, hit Save so you can revisit this architecture whenever you build your next ETL pipeline.
🏷️ Tags
#DataEngineering #AWS #ETL #Serverless #Lambda #S3 #SpotifyAPI
#Athena #Glue #DataPipelines #Python #CloudComputing
#ApacheSpark #RealTimeData