← Back to Learning Hub & Python Track
PUBLIC KNOWLEDGE GUIDE • TRACK 07 • MODULE 01
SOLUTION ENGINEER PERSPECTIVE ROOT CAUSE ANALYSIS (RCA) 10 SCENARIO DRILLS

Python Error Handling & Debugging for AdTech Solutions Engineers

We don't learn Python as an abstract academic subject. We learn it as a Solutions Engineer (SE) uses it: to investigate programmatic delivery failures, debug bidstream payloads, explain Root Cause Analysis (RCA), and communicate confidently with clients.

⚡ Start Level 1 ↓ 🛠️ Level 2: AdTech Debugging ↓ 👔 Level 3: Client RCA ↓ 🔥 10 Interview Drills ↓
LEVEL 1 • FOUNDATIONAL MECHANICS

Part 1 — Error Handling in Baby Steps

Imagine you have this simple campaign calculation:

spend = 1000
clicks = 50

cpc = spend / clicks
print(cpc)

Python calculates: 1000 / 50 = 20 → CPC = ₹20. Simple and predictable.

Now real production data arrives for a brand new CTV or video campaign:

spend = 1000
clicks = 0

cpc = spend / clicks
🚨 Python says: "I can't divide 1000 by zero." The script crashes instantly with a ZeroDivisionError and halts all downstream report processing.

Part 2 — Why try/except Exists

Think of try/except like a safety net. You tell Python: "Try this calculation. If this particular problem happens, don't crash the script. Do something sensible instead."

try:
    cpc = spend / clicks
    print("CPC:", cpc)
except ZeroDivisionError:
    print("No clicks yet.")

Now when spend = 1000 and clicks = 0, the output is graceful:

No clicks yet.
💡 The Core Mental Model:
TRY something
      ↓
Did it work?
   ↙       ↘
 YES        NO
 ↓           ↓
continue    EXCEPT block executes
LEVEL 2 • ADTECH DEBUGGING

Part 3 — Think Like an AdTech Solutions Engineer

Suppose your daily campaign delivery log reports:

Campaign: CTV_Brand_Awareness
Impressions: 500,000
Clicks: 0
Spend: ₹25,000

A junior developer writes cpc = spend / clicks, watches it crash, and treats it as a software bug.

An AdTech Engineer thinks differently:
"Zero clicks is actually a completely valid business state in CTV, DOOH, and awareness video advertising. It is not an application failure."
Campaign Data Situation Business Meaning SE Engineering Action
clicks = 0 Potentially valid (e.g. Connected TV or video completion campaign) Handle as undefined/null metric, do not crash
impressions = 0 Potentially valid (pacing start or unserved line item) Handle zero CTR/CPM calculation safely
spend = 0 Potentially valid (flight hasn't won auctions yet) Report ₹0 spend, skip eCPM floors
clicks = "500" Data-quality / string type mismatch Cast safely or flag ingestion pipeline parser
clicks = None Missing data or upstream null tracking Investigate whether beacon tracking was omitted
'clicks' key missing Schema change or broken API contract Handle KeyError and notify integration/SSP team

Part 4 — try/except Isn't the Whole Solution (Analytical Accuracy)

Consider this tempting shortcut:

try:
    cpc = spend / clicks
except ZeroDivisionError:
    cpc = 0  # ⚠️ DANGEROUS SHORTCUT

Technically the script doesn't crash. But is CPC = ₹0 correct?

❌ Absolutely not. If CPC is reported as ₹0, an automated bidding rule or media buyer will think clicks were free! In reality, clicks were 0, so CPC was mathematically undefined, not free.

The production-grade Solutions Engineer pattern:

try:
    cpc = spend / clicks
except ZeroDivisionError:
    cpc = None

if cpc is None:
    print("CPC cannot be calculated because attributed clicks are zero.")

Part 5 & 6 — Real API Problems: Multiple Exceptions & Missing Keys

In production REST APIs (GAM, SSP reporting, DSP bidstreams), data types often break:

# Problem 1: API passes numeric fields as strings
campaign = {
    "campaign_name": "CTV_A",
    "spend": "25000",   # String!
    "clicks": 500
}

# Dividing string by int raises TypeError!
try:
    cpc = float(campaign["spend"]) / float(campaign["clicks"])
except ZeroDivisionError:
    cpc = None
except (TypeError, ValueError):
    print("Invalid data format in API payload.")
except KeyError as err:
    print(f"Missing required schema field: {err}")

Part 7 — The Bigger Picture: Where Did the Error Originate?

In real AdTech troubleshooting, errors flow through multiple architectural layers:
SSP Reporting API
   ↓  (sends clicks = null due to SSAI beacon drop)
JSON Ingestion
   ↓  (parsed into Python dictionary)
Python Calculation
   ↓  (TypeError or ZeroDivisionError occurs)
Dashboard Display
   ↓  (shows N/A or breaks chart)
Client Email
   ↓  ("Why is our campaign reporting broken?")
Your job as a Solutions Engineer isn't merely "catch the Python error." Your job is to identify at which architectural layer the data broke and explain the business impact clearly.
LEVEL 3 • SOLUTION ENGINEERING & RCA

Part 8 — Expert-Level Interview Explanation

When an interviewer asks how you approach error handling in Python, deliver this verbatim framework:

"I use exception handling to separate expected business conditions from genuine application failures. For example, zero clicks in a Connected TV or high-impact video campaign is not an application error; it is a valid business state where CPC is mathematically undefined. However, if the clicks field is completely missing from an API response, that is a schema or integration issue and must be handled separately. I also strictly avoid silently converting uncalculable values to zero, because that creates misleading campaign KPIs and compromises financial billing accuracy."

Part 9 — Client Communication Practice (Talking to Non-Technical Stakeholders)

Imagine a high-value advertiser asks:

"Why is CPC showing as N/A for my campaign? We spent ₹50,000 yesterday! Is your system broken?"
❌ Junior / Dev Response (Too Technical)

"There was a ZeroDivisionError in our Python backend because clicks equals 0 and dividing by zero crashed the script, so our try/except returned null."

✅ Professional Solutions Engineer Response

"The campaign is delivering normally with active impressions and healthy delivery pacing. However, because CPC is calculated strictly as spend divided by clicks, the metric is mathematically undefined until the first click is attributed. Your spend and impression totals remain fully accurate."

PART 10 • INTERACTIVE PRACTICE

10 Senior Solution Engineer Interview & Client RCA Drills

Work through these 10 real-world production scenarios. Click each scenario to reveal the deep technical breakdown, engineering rationale, and client communication script.

Question 1 — Basic Debugging: Step-by-Step Execution Flow Mechanical Precision

Code:

spend = 5000
clicks = 0

try:
    cpc = spend / clicks
except ZeroDivisionError:
    print("No clicks")

Interviewer Question: "Walk me through exactly what happens when Python executes this code step-by-step."

🎯 Step-by-Step Execution Flow:
  1. Line 1: Variable spend is assigned integer value 5000 in memory.
  2. Line 2: Variable clicks is assigned integer value 0 in memory.
  3. Line 4: Python enters the try block scope.
  4. Line 5: Python attempts division 5000 / 0. The CPU detects division by zero, and the Python virtual machine immediately raises a ZeroDivisionError exception object. The assignment to cpc never occurs.
  5. Line 6: Python halts execution of the try block and searches for a matching except clause. It finds except ZeroDivisionError, which matches the raised exception type.
  6. Line 7: Python enters the except block and executes print("No clicks"), sending "No clicks" to standard output.
  7. Normal Exit: Because the exception was handled, the program does not crash and continues normal sequential execution.
Question 2 — AdTech KPI Problem: Reporting ₹0 vs N/A Data Integrity

Scenario: Spend: ₹10,000 | Impressions: 200,000 | Clicks: 0. Manager asks: "What's the CPC? Do we report ₹0 or N/A?"

SE Rationale: Always report N/A (or undefined/null). Reporting ₹0 implies cost was zero, meaning the advertiser received clicks for free. N/A communicates the mathematical reality: zero attributed clicks means cost per click cannot be calculated.
Question 3 — API Debugging: Missing Key & Integration Comms Integration Protocol

Scenario: API response omits 'clicks' key entirely. Script does clicks = response["clicks"].

Python Error: Raises KeyError: 'clicks'.
Explanation to Integration Team: "Our daily reporting ingestion pipeline failed on endpoint `/campaign/stats` because the JSON schema omitted the expected `clicks` key for campaign CTV_001. Please confirm if this is an intentional schema deprecation or if zero-click line items are omitting the field rather than returning `clicks: 0`."
Question 4 — Type Mismatch: Strings vs Numbers Type Safety

Scenario: API returns {"spend": "15000", "clicks": 500}. Script does spend / clicks.

Error: TypeError: unsupported operand type(s) for /: 'str' and 'int'.

Safe Solution: Never use plain int() because spend can be floating point (e.g. ₹15000.75). Use float() or decimal.Decimal wrapped in a try/except (TypeError, ValueError) check to validate input cleanliness.
Question 5 — Production Troubleshooting: CPC Disappears (3 Hypotheses) RCA Thinking

Scenario: Yesterday CPC was ₹20. Today CPC is N/A, but spend is ₹50,000 across 2M impressions. Do you immediately blame click tracking?

3 Alternative Engineering Hypotheses:
  1. Inventory Shift to Non-Clickable Formats: Campaign shifted budget to Connected TV (CTV) or DOOH inventory where click macros are intentionally non-existent.
  2. Click Tracker / VAST 4.2 Macro Failure: Creative agency swapped tags with unexpanded or corrupted [CLICK_URL] macros, failing redirect resolution.
  3. Attribution Window / Timezone Cutoff: Reporting query pulled intraday before MMP (AppsFlyer/Branch) batch attribution sync completed.
Question 6 — Don't Hide Errors: The Danger of Bare Except System Safety

Scenario: Developer writes except: cpc = 0 claiming "the script never crashes."

Catastrophic Real-World Impact: A bare except: catches everything — including typos in variable names (NameError), memory errors (MemoryError), and keyboard interrupts. In AdTech, setting cpc = 0 on errors will mask billing discrepancies, causing automated bid optimizers to bid infinite budget on broken inventory because they think clicks are free!
Question 7 — Batch Pipeline RCA: Handling nulls in 100k records Data Pipeline

Scenario: Processing 100,000 campaign records. One record has clicks = None.

Solution Engineer Best Practice (Option D - Isolate & Dead-Letter): Do not abort the 99,999 valid records. Isolate the malformed record, write it to a Dead Letter Queue (DLQ) or error audit log with campaign ID and timestamp, calculate CPC as None with an explanatory status flag, and generate an automated alerting metric.
Question 8 — Client Communication: Explaining API Null without Jargon Client Poise

Scenario: Client claims reporting is broken because CPC disappeared due to an upstream API sending clicks = null.

Client Email Script:
"Thank you for reaching out. Your campaign delivery and impressions are running smoothly with no disruption to your ad serving. We noticed that our partner reporting feed is currently synchronizing click verification data, causing the CPC metric to temporarily appear as uncalculated. We have expedited the data refresh with our technical partners and expect full metric visibility within the next 2 hours."
Question 9 — Senior SE Scenario: Programmatic Funnel Breakdown Funnel Architecture

Funnel: Requests: 10M | Bids: 2M | Wins: 100K | Impressions: 90K | Clicks: 0 | Spend: ₹50K. Python hits ZeroDivisionError.

Senior Investigation Plan:
  • KPI Causing Error: CPC (spend / clicks) or Click-to-Win Rate (clicks / wins).
  • Critical Funnel Observations: Win Rate = 5% (100K/2M), Win-to-Impression Drop = 10% (100K wins vs 90K imps — VAST timeout or rendering failure).
  • Questions for DSP/SSP: "Are win notices (nurl) firing without corresponding billing beacons (burl)? Are VAST creative wrappers timing out before the click-through element is injected?"
Question 10 — Final Boss: Complete RCA & Client Remediation Senior Master Drill

Scenario: Client: "Our CTV campaign spent ₹2 lakh yesterday, but your dashboard shows N/A for CPC. Your platform is clearly broken."

campaign = {
    "campaign_id": "CTV789",
    "spend": "200000",
    "impressions": 5000000,
    "clicks": None
}
try:
    cpc = spend / clicks
except ZeroDivisionError:
    cpc = None
10-Point Technical & Business Audit:
  1. Data Type Bug: spend is a string, not numeric.
  2. Missing Data Bug: clicks is None, which raises TypeError, not ZeroDivisionError! The code would still crash!
  3. KPI Definition: CTV is non-clickable television inventory; CPC is not the KPI — Video Completion Rate (VCR) and eCPM are the primary metrics.
  4. Client Communication: Reassure the client immediately that ₹2 lakh was served across 5,000,000 verified households with a 96% completion rate. Explain that CTV ads run on living-room TVs without mouse clicks, so CPC is legitimately not applicable.
  5. Remediation: Cast numeric types safely, catch (TypeError, ZeroDivisionError), and conditionally hide click-centric KPIs for CTV channel placement objects.

Ready to Test More Solution Engineering Workflows?

Explore our full 8-track interactive engineering curriculum or access the password-protected Solution Engineering scenario bank.

📊 Explore AdTech SQL Masterclass → 🐍 Back to Python Track 🔐 Open Study Portal

AdTech Toolkit

Enter any two values
to calculate the third

More tools coming soon