Amazon Logistics: Rescue a Slow Shipment Validation Pipeline (PySpark)
PYSPARK coding challenge · Difficulty: hard · Topic: Performance Optimization · +150 XP
Topics: RDD mapPartitions() · Partition-level setup · Regex validation · Data quality · Performance
*A fictional logistics case study inspired by large-scale e-commerce systems, not a verified Amazon interview question.*
The Production Incident
It's 9:00 AM on the first day of a major shopping festival. Millions of packages are entering the logistics network, and before a package can ship, its tracking label must be validated against carrier rules.
The legacy job builds a brand-new validator for every shipment. Each one compiles the carrier's label rules again. On a quiet day nobody noticed; today the validation stage is the slowest step in the whole pipeline and the dispatch queue is growing.
Your engineering lead's request:
- Build the rule engine once per partition, not once per record.
- Validate every shipment and give each one exactly one status. Nothing is dropped.
- Charge a handling fee for valid shipments.
- Return the results as a PySpark DataFrame.
You'll do it with RDD.mapPartitions().
Input Data
You receive a DataFrame named shipments:
| Column | Data type | |---|---| | shipment_id | Integer | | service | String | | tracking_code | String (may be NULL, blank, padded or lowercase) | | weight_kg | Double (may be NULL) |
Your Tasks
Task 1: Initialise the rule engine once per partition
Write a function process_partition(rows). At the top of it, before the loop, compile the label rules with re.compile():
| Service | Required format | Valid example | |---|---|---| | EXPRESS | `EX-CC-NNNN` | `EX-US-1234` | | STANDARD | `ST-CC-NNN` | `ST-IN-090` |
CC is exactly two uppercase English letters, NNNN exactly four digits and NNN exactly three digits. The whole code must match: use fullmatch() (or anchor the pattern). EX-US-12345 is not valid just because it starts with EX-US-1234.
Task 2: Normalise the tracking code
Create normalized_code: trim leading and trailing whitespace and convert to uppercase, so " ex-us-1234 " becomes EX-US-1234. If the code is NULL, or empty after trimming, normalized_code is NULL.
Task 3: Validate each shipment
Create validation_status. Check the rules in this order; the first rule that fails decides the status:
| Priority | Condition | Status | |---|---|---| | 1 | Tracking code missing or blank | `MISSING_CODE` | | 2 | Service is not exactly `EXPRESS` or `STANDARD` | `UNSUPPORTED_SERVICE` | | 3 | Code does not match its service's format | `INVALID_FORMAT` | | 4 | Weight is NULL or less than or equal to 0 | `INVALID_WEIGHT` | | 5 | All checks pass | `VALID` |
Only the tracking code is normalised. The service is compared exactly as stored, so express, an empty string and NULL are unsupported.
Task 4: Calculate the handling fee
For a VALID shipment, first round the weight up to whole kilograms (2.2 kg becomes 3 kg; 2.0 kg stays 2 kg), then:
| Service | handling_fee | |---|---| | EXPRESS | 50 + 10 × kilograms | | STANDARD | 20 + 5 × kilograms |
Every other shipment has handling_fee = 0.
Task 5: Run it with mapPartitions()
Apply your function with shipments.rdd.mapPartitions(process_partition). The function receives an iterator of rows and must:
- build the rules once, then stream the rows (
yieldone output record per input record); - not turn the whole partition into a list;
- work for an empty partition (it simply yields nothing).
Convert the resulting RDD back to a DataFrame with an explicit schema.
Example 1
Input: shipments (the quotes only show the spaces inside a code)
| shipment_id | service | tracking_code | weight_kg | | --- | --- | --- | --- | | 501 | EXPRESS | `" ex-us-1234 "` | 2.2 | | 502 | STANDARD | ST-IN-090 | 1.0 | | 503 | EXPRESS | EX-UK-12 | 3.0 | | 504 | STANDARD | NULL | 4.0 | | 505 | PRIORITY | PR-US-1234 | 2.0 | | 506 | EXPRESS | EX-DE-8888 | 0.0 | | 507 | STANDARD | `" st-jp-007 "` | 2.1 | | 508 | EXPRESS | `" "` | 1.0 | | 509 | STANDARD | ST-FR-321 | NULL | | 510 | EXPRESS | EX-CA-4321 | 1.0 |
Expected output:
`
+-----------+--------+---------------+-------------------+------------+
|shipment_id| service|normalized_code| validation_status|handling_fee|
+-----------+--------+---------------+-------------------+------------+
| 501| EXPRESS| EX-US-1234| VALID| 80| | 502|STANDARD| ST-IN-090| VALID| 25| | 503| EXPRESS| EX-UK-12| INVALID_FORMAT| 0| | 504|STANDARD| NULL| MISSING_CODE| 0| | 505|PRIORITY| PR-US-1234|UNSUPPORTED_SERVICE| 0| | 506| EXPRESS| EX-DE-8888| INVALID_WEIGHT| 0| | 507|STANDARD| ST-JP-007| VALID| 35| | 508| EXPRESS| NULL| MISSING_CODE| 0| | 509|STANDARD| ST-FR-321| INVALID_WEIGHT| 0| | 510| EXPRESS| EX-CA-4321| VALID| 60|
+-----------+--------+---------------+-------------------+------------+
`
Understanding Your Result
- 501
" ex-us-1234 "is trimmed and uppercased toEX-US-1234, a valid EXPRESS label. 2.2 kg rounds up to 3 kg: 50 + 10 × 3 = 80. - 503
EX-UK-12has two digits instead of four:INVALID_FORMAT. - 504 and 508 have no usable code (NULL and only spaces), so
normalized_codeis NULL and the status isMISSING_CODE. - 505 PRIORITY is not a supported service, even though its code looks well formed.
- 506 and 509 have perfect labels but no usable weight (0 kg and NULL):
INVALID_WEIGHT. - 507
" st-jp-007 "becomesST-JP-007; 2.1 kg rounds up to 3 kg: 20 + 5 × 3 = 35. - 510 weighs exactly 1.0 kg, which stays 1 kg: 50 + 10 × 1 = 60.
Constraints
- Output exactly
shipment_id,service,normalized_code,validation_status,handling_fee, sorted byshipment_idascending.handling_feeis an integer. - Keep every shipment: one output row per input row, invalid ones included.
shipments,sparkandF(pyspark.sql.functions) are ready. Do not recreateshipmentsand do not hard-code the example output.- Your code also runs on hidden datasets with other codes, services and weights. Some partitions may be empty, and the input may be in any order.
- Do not use
.collect(),.toPandas(), row-wise UDFs orrdd.map()in place ofmapPartitions(). - Assign the result to
df_resultand finish withdf_result.show().
Interview Bonus
Be ready to answer:
1. Why can mapPartitions() beat a row-wise Python UDF when setup is expensive?
2. Why should a partition function yield records instead of building one large list?
3. When are native DataFrame expressions better than mapPartitions()?
Engineering principle: optimise the expensive work, not just the syntax.
What this PYSPARK challenge teaches you
“Amazon Logistics: Rescue a Slow Shipment Validation Pipeline (PySpark)” is a hard-level PYSPARK challenge focused on Performance Optimization. Working through it gives you hands-on practice with mapPartitions, RDD, Regex validation, Data quality, Performance — the kind of transformation you are asked to write in real data engineering work and in technical interviews. You can solve it directly in the browser: the dataset is pre-loaded, so you write the query or DataFrame code, run it, and compare your output against the expected result immediately.
Concepts covered
- mapPartitions
- RDD
- Regex validation
- Data quality
- Performance
How to approach it
If you get stuck, work through these steps in order before looking at a full solution — each one narrows the problem down:
- Put the expensive setup at the top of process_partition(rows): rules = {'EXPRESS': re.compile(r'EX-[A-Z]{2}-[0-9]{4}'), 'STANDARD': re.compile(r'ST-[A-Z]{2}-[0-9]{3}')}. Then loop: for row in rows: ... yield (...).
- Normalise first: code = raw.strip().upper() if raw is not None else None, then code = code or None so a blank code becomes NULL. Check the statuses in order with if/elif, and use rules[service].fullmatch(code): match() would accept EX-US-12345.
- The fee uses math.ceil(weight): 2.2 -> 3 but 2.0 -> 2. Invalid shipments get 0, not NULL.
- Build the DataFrame with an explicit schema: spark.createDataFrame(shipments.rdd.mapPartitions(process_partition), schema) where schema is a StructType of shipment_id INT, service, normalized_code, validation_status STRING and handling_fee INT. Then orderBy('shipment_id').
Interview practice
This problem is good practice for data engineering interviews at companies such as Amazon. Interviewers use problems like it to check whether you can express the logic cleanly and reason about correctness on edge cases such as ties, nulls and empty groups.
How to practise it on PySpark.in
Open the challenge, write your PySpark code in the editor and press Run to execute it against the sample dataset. Submitting checks your output against every test case, including hidden ones, so you find out straight away whether your logic holds up. You can retry as often as you like, and each solved challenge adds to your XP.
Related PYSPARK challenges
- Handle Data Skew from High-Frequency Vehicles (PySpark)
- Salting a Skewed Join: Customer Bucket Load Report (PySpark)
- Fix the Broken Pipeline
- Optimize the 100M-Row Join
- Parse Apache Logs with Regex
- Optimize Small DataFrame Join with Broadcast
Helpful resources
Frequently asked questions
Do I need to install Spark or a database to solve this?
No. The PYSPARK environment runs in your browser with the sample data already loaded, so there is nothing to install or configure.
Is this challenge free?
Yes - the problem, the sample dataset, the hints and unlimited test runs are free.
What level is it?
It is rated hard and covers Performance Optimization.