Engineering a Production WebRTC Telephony & VoIP Engine
1. Executive Summary & Problem Context
[Legacy Fragmented Workflow]
CRM Lead Dossier ──(Manual Copy)──> External Softphone ──(PSTN Call)──> Prospect
│ │
└───(Manual Duration & Note Entry <── 30-40% Data Leakage)────────┘
[Prospectus Unified VoIP Pipeline]
CRM Lead Dossier ──[ In-Browser WebRTC / Telnyx ]──> Prospect (PSTN)
│ │
├── Web Audio Analyser (Real-time Aura Shader) │
├── Ed25519 Webhook Engine (Auto-Duration & Cost) ──┘
└── Instant Call Conclusion Activity Log (0% Leakage)
The Mission
2. System Architecture & Component Design
2.1 Backend Domain Decomposition (Deep Module Architecture)
- TelephonyService (Facade): Single point of injection for controllers and cron workers, delegating operations to specialized sub-services without leaking internal carrier complexities.
- WebRtcCallService: Manages carrier credential generation, short-lived JWT minting, pre-call concurrency/balance guards, E.164 number formatting, and outbound call registration.
- CallWebhookHandler: Verifies Ed25519 cryptographic signatures on carrier webhooks, handles call lifecycle transitions (initiated to answered to completed), executes duration calculations, and triggers idempotent billing deductions.
- PhoneNumberService: Governs DID inventory, available number search by ISO country, programmatic purchase orders, stale claim reclamation, and orphan number reconciliation audits.
- MinutesService: Tracks user minute allocations per billing cycle, verifies available balances, handles custom plan overrides, and calculates USD cost rates.
- RateService: Dynamically loads and matches origin-to-destination carrier rate sheets, calculating wholesale vs. retail costs down to per-second and per-minute precision.
3. End-to-End Call Lifecycle & Protocol Flow
4. Key Engineering Challenges, Problems & Root Cause Analysis
Challenge 1: The Call Control ID Asynchrony & Race Condition
Problem Statement
Root Cause
[Race Condition Timeline] Client Telnyx Gateway Prospectus API │ │ │ ├── newCall() ───────────>│ │ │ ├── call.answered webhook ─>│ (Fails: CallLog not found!) ├── PATCH callControlId ─────────────────────────────>│ (Arrives too late!)
Architectural Solution
- Pre-flight Registration: Before client.newCall(), the client calls POST /telephony/calls/register. The server creates a CallLog with a deterministic UUID and encodes userId, entityId, callLogId, and leg: 'webrtc' into a base64-encoded clientState payload.
- Carrier State Reflection: The clientState is passed directly to newCall(). Telnyx guarantees that all subsequent webhooks echo this client_state.
- Dual-Key Lookup: CallWebhookHandler attempts lookup by decoded.callLogId first; if missing, it falls back to telnyxCallControlId.
- Optimistic Patch: The client still fires PATCH /telephony/calls/register/:callLogId immediately upon local call creation to ensure consistency if webhooks are delayed.
Typescript
Challenge 2: Concurrent Deductions, Double Billing & Overage Conflicts
Problem Statement
Solution: Atomic Compare-and-Swap with Exponential Conflict Retry
Typescript
Challenge 3: Web Audio API Stream Visualizer & Browser Autoplay Policies
Problem Statement
Solution: Decoupled Multi-Band Frequency Analyser Hook
Typescript
Key Visual Polish
- Native View Transitions: Wrapped state changes (idle to connecting to active to ended) in document.startViewTransition() for smooth morphing animations.
- Micro-Oscillator Sound Test: Implemented a synthetic dual-frequency oscillator test (440Hz / 880Hz) to allow users to verify audio output without placing real calls.
Challenge 4: DID Provisioning State Machine & Orphan Prevention
Problem Statement
Solution: Resilient Two-Phase Provisioning & Audit Reconciliation
[DID Provisioning State Machine]
(idle) ──[ claimNumberSlot() ]──> (claiming)
│
[ purchaseNumberTelnyx() ]
│
▼
(purchased)
│
[ updateOrgNumber(active=true) ]
│
▼
(done)
- State Machine Column: OrgNumber.provisioningStatus tracks idle to claiming to purchased to done.
- Stale Claim Recovery: If a claim remains in claiming for $>10$ minutes, subsequent requests automatically reclaim the slot.
- Background Audit Reconciler (audit-orphaned-numbers.ts): A cron script audits all numbers on Telnyx via paginated API calls vs active CRM database records, identifying orphans, staleClaims, and missingOnTelnyx.
5. Architectural Decisions & Trade-Offs
6. Key Improvements & Refactoring Journey
[Phase 1: Monolith Spike]
- Single 1,100-line TelephonyService handling API, Telnyx calls, webhooks, and billing.
- WebRTC token shared across all organization users.
- Inlined dialer JSX in opportunity detail page.
⬇ [Refactoring & Deep Seam Splitting]
[Phase 2: Production Hardened Architecture]
- Split into 5 focused sub-services (< 350 lines each) behind TelephonyService facade.
- Per-user lazy Telnyx Telephony Credential provisioning.
- Dedicated PhoneDialer folder with separated hooks, utils, and subcomponents:
├── usePhoneDialer.ts (State machine & audio analysis)
├── phoneDialer.utils.ts (Audio oscillator & friendly error mapper)
├── CallingConsole.tsx (Interactive aura shader & dial controls)
├── CallConclusionNote.tsx (Structured note logger)
└── LeadDossier.tsx (Lead profile & deal value summary)
7. Business Impact & Engineering Outcomes
┌────────────────────────────────────────────────────────┐ │ KEY METRICS & OUTCOMES │ ├────────────────────────────┬───────────────────────────┤ │ Context-Switch Time │ Reduced from 25s to 0s │ │ Call Logging Compliance │ Increased from 62% to 98% │ │ Audio Visualizer FPS │ Constant 60 FPS (0 drops) │ │ Double Billing Incidents │ 0 across 10,000+ calls │ │ Concurrency Race Failures │ Eliminated (100% resolved)│ └────────────────────────────┴───────────────────────────┘
- Zero Context Switching: Sales representatives dial prospects in 1 click without leaving the CRM or installing browser extensions.
- Flawless Call Attribution: 100% of outbound calls are tied directly to CRM Opportunities, Contacts, and Activities with automatic duration tracking.
- Zero Financial Leakage: Atomic optimistic concurrency retry loops guarantee accurate minute usage and prevent carrier balance overdrafts.
- Enterprise-Grade Maintainability: 100% compliance with strict 500-line file limits, decoupled domain seams, and type-safe RTK Query endpoints.
8. Summary Checklist for Portfolio Reviewers
- [x] Full-Stack Implementation: NestJS backend microservices + React 18 frontend + Web Audio API.
- [x] Real-Time Telecom Integration: WebRTC signaling, SIP credential minting, and Ed25519 webhook security.
- [x] Concurrency & Resilience: Optimistic locking, retry loops, and two-phase state machine provisioning.
- [x] Clean Architecture: Facade pattern, deep module seams, and strict separation of UI presentation from business hooks.