E-commerce customer behavior analysis on a PySpark medallion pipeline
A completed e-commerce analytics project: batch and real-time PySpark paths move orders through raw, bronze, silver and gold so segmentation, churn risk and satisfaction prediction read one customer row.
Our client, an e-commerce business, held customer and order data but could not answer three questions from it: which customers belong together, which ones are unlikely to buy again, and how satisfied a given customer is likely to be. We built a PySpark pipeline to answer them. It ran a batch path over stored history and a real-time path over incoming events, and both paths moved data through the same layers. Raw exports and live events landed in bronze as validated records, stored as they arrived. Silver cleaned and enriched them. Gold aggregated them into one row per customer. The client's data analysts, marketing and retention team and data scientists read that gold row through their analytics tools, and the segmentation, churn-risk scoring and satisfaction prediction all started from it.
Three questions, one customer row
The first question was segmentation. The client wanted customers grouped by demographics, meaning age, gender and city, and by shopping behavior, meaning total spend, number of items purchased and membership type. That is six fields, and each one had to be defined once and filled for every customer before a grouping meant anything.
The second was churn risk. Which customers were unlikely to purchase again, judged by days since their last purchase and their satisfaction level? This question goes stale fast. A risk list built from last month's export names people who already came back and misses the ones who stopped last week.
The third was prediction. The client wanted to estimate a customer's satisfaction level from demographic and purchase history data. A model learns whatever mistakes its training data carries, so this question set the highest bar for cleaning.
Put side by side, the three read almost the same columns. So we built one customer table and pointed all three at it instead of preparing data three times. In our view that was the most useful decision in the project.
Why raw data could not answer them
Raw e-commerce data is organised around transactions. The questions were about customers.
Order data has one row per purchase, so a customer who ordered five times appears in five rows. Total spend and item counts do not exist anywhere in that data; they have to be summed per customer. Days since last purchase does not exist either. It is a calculation against a reference date, and two analysts who pick different dates get two different risk lists.
Demographics and behavior sit in different places. Age, gender and city describe the customer. Spend and items come from orders. Membership type and satisfaction level have to be attached to the same person. A question that needs all of them in one row needs a join, and a join on dirty keys drops customers who fail to match or doubles the ones who appear twice.
Then there is the ordinary mess. Typed fields such as city arrive in more than one spelling, overlapping exports repeat orders, and live events arrive one at a time with no history attached. An answer computed straight from that is an answer about the export, not about the customers.
What we built
The brief was an ETL pipeline that made cleaned e-commerce data available to downstream analytics tools. We built it in Python on Apache Spark.
Spark did the distributed processing. A Spark application has a driver that splits work into tasks and sends them to executors on the cluster (Spark cluster mode overview). For us that meant a transformation written once in PySpark ran in parallel over partitions of the data, and a larger input was a question of executors rather than code.
The layers followed the medallion pattern. Databricks describes bronze as raw data ingestion, silver as cleaning and validation, and gold as dimensional modelling and aggregation (medallion architecture). We put a raw layer in front of bronze to hold files and events exactly as they arrived.
Every transformation worked on Spark DataFrames, which the Spark documentation defines as Datasets organised into named columns (Spark SQL and DataFrames). Named columns sound like a small thing. In practice a rule such as "normalise city" pointed at the same city column in every layer, and a schema change broke a test before it reached a report.
From raw file to customer row
- Raw order and customer exports and live shopping events landed in the raw layer unchanged.
- Bronze validated the incoming records and stored them as they arrived. Nothing was corrected at this stage, so any later rule could be rerun against the original data.
- Silver cleaned the records. Duplicates were removed and typed values such as city were brought to one spelling.
- Silver enriched the cleaned records with features computed from purchase history, among them total spend, number of items purchased and days since last purchase.
- Gold aggregated the result into one row per customer, with age, gender, city, membership type, total spend, items purchased, days since last purchase and satisfaction level side by side.
- Analytics tools and the three analyses read gold. Nothing downstream read silver or bronze.
Step six mattered most to us. When a cleaning rule changed in silver, gold was rebuilt from it and every report picked up the change in the same run.
Batch history and live events
The client wanted both batch data analysis and real-time data processing, so the pipeline had two entry paths.
The batch path ran over stored history and rebuilt gold from the full record. Segmentation and the satisfaction model need that view, since a customer's spend and item count only mean something across all of their orders.
The real-time path processed incoming shopping events as they arrived, so recent activity reached the customer row between batch runs. For churn risk this was the point. A customer who bought something this morning should drop off the risk list today, not after the next scheduled job.
Spark's Structured Streaming lets a streaming computation be written the same way as a batch computation on static data, and runs it incrementally as new data arrives (Structured Streaming). We relied on that. The cleaning and enrichment rules were written once against DataFrames and used by both paths. Two implementations of "total spend" is how a batch report and a live view end up disagreeing, and we did not want to explain that gap to an analyst.
Two paths are more work to run and test than one. We think it was the right call: history answers questions about customers over time, events answer questions about this week.
Segments, risk and a satisfaction prediction
All three analyses ran on gold, never on the raw files.
For segmentation, feature engineering turned the six fields into model inputs. Age, spend and item counts are numbers on very different scales. Gender, city and membership type are categories. Spark's ML library documents transformers for this kind of preparation, such as encoders for categorical columns and assemblers that combine several columns into one feature vector (MLlib feature transformers). The output we cared about was a segment label an analyst could put into a campaign and trace back to real customers.
For churn risk, we kept the definition in plain view. Days since last purchase and satisfaction level were both gold columns, so the at-risk group was recalculated on every load. A customer who slipped into the group this week showed up this week, and nobody had to reopen a spreadsheet to find them.
For satisfaction, the inputs were the demographic and purchase history fields and the target was the satisfaction level customers had recorded. A predicted score for a customer who never gave one is a useful signal for targeting. It is still a prediction, and nobody should read it as something a customer said.
The modelling was the short part. Most of the effort went into definitions: what counts toward total spend, which date days since last purchase is measured from, what to do with a customer who has no satisfaction value. We settled those once in the pipeline instead of once per report, which is why the analyses could be rerun rather than rebuilt.
Tests and configuration
Unit tests covered single transformations, one rule at a time: duplicate removal, city normalisation, the days since last purchase calculation. Integration tests pushed a small dataset through raw, bronze, silver and gold and compared the gold output with expected rows. The bugs that hurt most in a pipeline like this, such as a join that drops customers or a column renamed in one layer and not the next, only show up at that level.
The YAML configuration held the values that change between environments, such as input and output paths and run parameters. Moving the pipeline or renaming a table was an edit to one file, and the transformation code never had to know where it was running.
Teams often cut tests and configuration first when a deadline gets close. Here both shipped with the pipeline, and we think they matter more than any single transformation for keeping it running after handover.
Conclusion
The client ended up with one path from raw e-commerce data to answers about its customers. Batch runs covered history, the real-time path covered the current day, and segmentation, churn-risk scoring and the satisfaction prediction all read the same gold row.
The gold row outlasted the three questions that started the project. It held spend, recency, membership and satisfaction for every customer, so a new question about customers began with that table instead of a fresh export and a fresh argument about which number was right.