Call Us NowRequest a Quote
Back to Blog
Kotlin Multiplatform
May 23, 2024
15 min read

Architecting a DPDP-Native B2B Lead Engine - Kotlin Multiplatform, Meta CAPI & Next-Gen ERP

Induji Technical Team

Induji Technical Team

Content Strategy

Architecting a DPDP-Native B2B Lead Engine - Kotlin Multiplatform, Meta CAPI & Next-Gen ERP

Key Takeaways

  • Mobile-First B2B is a Reality: High-value B2B decision-makers are increasingly engaged on mobile-centric platforms like Instagram and LinkedIn. An optimized native app experience for lead capture significantly outperforms clunky web forms.
  • Closed-Loop Architecture: The definitive architecture for 2026 involves a data flow from a Kotlin Multiplatform (KMP) App to a Next-Gen ERP, which then triggers qualified conversion events to the Meta Conversions API (CAPI). This ensures Meta's algorithm optimizes for business value, not just form fills.
  • DPDP-Native by Design: Engineering compliance with India's DPDP Act 2023 is non-negotiable. This architecture embeds consent management and data minimization principles directly into the KMP shared logic and ERP workflows, creating a machine-checkable audit trail.
  • ERP as the Source of Truth: Instead of firing conversion events from the client-side, the Next-Gen ERP acts as the validation engine. An event is only sent to Meta CAPI after a lead is qualified by sales or an automated workflow, dramatically improving signal quality.
  • Event-Driven for Resilience: An event bus like Apache Kafka or AWS EventBridge decouples the ERP from the CAPI service, creating a scalable, resilient, and fault-tolerant pipeline that can handle high volumes and guarantee data delivery.
  • Tech Stack Synergy: The combination of KMP (using Ktor for networking and SQLDelight for offline storage) for the front end, a modern ERP, and a dedicated microservice for CAPI integration provides the optimal blend of native performance, business logic integrity, and compliance.

The New B2B Battlefield: High-Intent Mobile Leads

For years, B2B lead generation was a desktop-centric game of lengthy whitepaper forms and webinar sign-ups. This paradigm is fundamentally broken in 2026. Your next high-ticket enterprise client is just as likely to discover your solution while scrolling through their Instagram feed on their iPhone as they are searching on a desktop. The challenge is no longer just reaching them, but capturing their intent in a seamless, trustworthy, and compliant manner.

Simply redirecting a mobile ad to a non-responsive, multi-field web form is a recipe for abysmal conversion rates. The modern B2B buyer expects a native, fast, and secure experience. Furthermore, with the enforcement of India's Digital Personal Data Protection (DPDP) Act 2023, the old "capture-everything" approach is a significant legal and financial liability.

This article provides a senior-level architectural blueprint for a system that addresses these challenges head-on. We will architect a closed-loop, DPDP-native B2B lead engine that leverages a Kotlin Multiplatform mobile app for superior user experience, a Next-Gen ERP as the single source of business truth, and the Meta Conversions API for unparalleled ad optimization. This is how you build a durable competitive advantage.

Core Architectural Blueprint: A Component-Level Deep Dive

This architecture is designed for data integrity, scalability, and compliance. It intentionally separates concerns to ensure each component performs its function optimally, creating a robust and auditable data pipeline from the first touchpoint to revenue attribution.

Architecture diagram showing the data flow from a Meta Ad to a Kotlin Multiplatform App, then to a Next-Gen ERP, and finally to Meta Conversions API.

The flow is as follows:

  1. A user clicks a Meta Ad (Facebook/Instagram) and is deep-linked into the Kotlin Multiplatform App.
  2. The user interacts with a native lead form, provides explicit DPDP-compliant consent, and submits their data.
  3. The KMP app securely sends the lead data and a unique event_id to your backend API Gateway.
  4. The backend ingests the data and creates a new "Lead" record in your Next-Gen ERP.
  5. Internal business processes (manual sales qualification or automated workflows) update the lead's status in the ERP (e.g., from New to Marketing Qualified Lead).
  6. The ERP publishes a lead.qualified event to a message bus (e.g., Kafka).
  7. A dedicated "CAPI Microservice" consumes this event, formats a payload including the original event_id and hashed user data, and sends it to the Meta Conversions API.

Let's dissect each component.

The Frontline: Kotlin Multiplatform (KMP) Mobile App

The choice of KMP is strategic. It allows us to write the most critical, complex logic once in a shared Kotlin module while building fully native UIs for the best possible performance and user experience on both iOS and Android.

  • Shared Logic (KMM Core): This is the heart of the app. It contains:

    • Data Models: Strict data classes for leads, consent objects, and API responses using kotlinx.serialization.
    • Validation Logic: Shared rules for validating inputs like email, phone number, and business details.
    • DPDP Consent Management: A dedicated module to manage consent states, purposes, and timestamps. This logic is written once and guaranteed to be identical on both platforms.
    • Networking: A Ktor-based HTTP client for all API communication, configured with standard headers, authentication, and retry logic.
    • Offline Storage: Using SQLDelight to store lead submissions locally if the device is offline, ensuring data is never lost and can be synced when connectivity is restored.
  • Platform-Specific UI: We leverage the best of each platform:

    • Android: Jetpack Compose is used to build a dynamic, reactive UI that feels perfectly at home on Android.
    • iOS: SwiftUI provides a modern, declarative way to build a pixel-perfect iOS interface. Both UIs communicate with the same shared KMM Core ViewModel, ensuring consistent behavior.
  • Data Capture & Consent: The lead form itself is an engineered component. It features a clear, unambiguous consent checkbox with a link to the privacy policy. The consent text explicitly states the purposes of data processing: "To contact you regarding your inquiry" and "To improve our advertising by sending anonymized conversion signals." This granularity is key to DPDP compliance.

The Central Nervous System: Next-Gen ERP

Your ERP (whether it's ERPNext, Odoo, SAP S/4HANA, or a custom-built solution) is elevated from a mere accounting tool to the core of your marketing intelligence. It is the arbiter of truth for lead quality.

  • API Ingestion: The ERP system exposes a secure REST API (or consumes from an internal queue) to receive the raw lead data from the KMP app.
  • The Qualification Workflow: This is the critical value-add. A form fill is not a conversion; a qualified lead is. The ERP implements the business logic to determine this. This could be:
    • Automated Scoring: A system that scores leads based on company size, industry, or job title.
    • Sales Development Rep (SDR) Triage: An SDR manually reviews the lead and updates its status to "Qualified" or "Junk."
    • First Meeting Booked: The status is updated automatically when a meeting is booked via a connected calendar integration. Only when the lead's status changes to a pre-defined "conversion" state does the ERP initiate the next step.

The Feedback Loop: Event-Driven Pipeline to Meta CAPI

Sending conversion events directly from the app is a rookie mistake. It leads to signal inflation (counting junk leads), security vulnerabilities, and an inability to attribute real business value. An event-driven server-side pipeline is the professional standard.

  • Event Publishing: When a lead is qualified, the ERP doesn't call the Meta API directly. Instead, it publishes a domain event like lead.qualified or opportunity.created to a message bus like Apache Kafka or AWS EventBridge. The event payload contains the lead ID, the event_id generated by the app, and necessary user data.
  • Decoupling with a Message Bus: This is a crucial architectural decision. It decouples the ERP's core functionality from the marketing integration. If the Meta CAPI is down or your CAPI service fails, the events remain safely in the queue to be processed later. The ERP's performance is unaffected.
  • The CAPI Microservice: This is a small, dedicated service (written in Go, Rust, Node.js, or Kotlin) with one job: consume events from the message bus, transform them into the format required by the Meta Conversions API, and send them securely. This service handles PII hashing, access token management, and error logging, isolating this logic from the rest of your stack.

Engineering DPDP Compliance from First Touch to Conversion

This architecture isn't just "DPDP-aware"; it's "DPDP-native." Compliance is an engineered feature, not an afterthought.

Principle of Consent & Purpose Limitation in KMP

The DPDP Act mandates clear, informed consent for specific purposes. Our KMP app architecture enforces this at the point of collection.

  1. Granular Consent UI: The UI presents separate, unchecked boxes for each distinct purpose of data processing.
  2. Shared Consent Logic: The KMM Core contains a ConsentManager class that captures the user's choice, the exact text they consented to, and a cryptographic timestamp.
  3. Data Transmission: The consent object is bundled with the lead data and sent to the ERP. The CAPI service will later check for advertising_consent_given == true before processing an event for Meta. If consent is not given for this purpose, the event is dropped, creating a machine-checkable compliance gate.

Data Fiduciary Responsibility: The ERP's Role

Under the DPDP Act, your organization is the Data Fiduciary. The ERP is the system of record where you enact this responsibility.

  • Data Minimization: The CAPI service should be configured to only pull the minimum data required from the event payload. Meta requires hashed PII (email, phone), event_id, and event details. It does not need the lead's company name, message content, or other sensitive business details. This pipeline ensures that extraneous data never leaves the secure boundary of your ERP for marketing purposes.
  • Access Control: The CAPI service connects to the message bus with credentials that only grant it access to the specific marketing.conversions topic, adhering to the principle of least privilege.

A flowchart visualizing the DPDP compliance checkpoints at each stage of the data pipeline, from app consent to ERP validation and CAPI service filtering.

Machine-Checkable Compliance & Audit Trails

In the event of a data audit, you must be able to prove compliance. This architecture provides an end-to-end audit trail.

  • App: The local SQLDelight database contains a log of consent actions.
  • API Gateway: Ingestion logs show the raw payload received from the app, including the consent object.
  • ERP: The lead's record has a full history, showing when it was created, who qualified it, and when the lead.qualified event was published.
  • CAPI Service: Structured logs (e.g., JSON format) record every event consumed, the decision made (send or drop based on consent), and the response from the Meta API.

This chain of evidence is irrefutable proof of a compliant, consent-driven process.

Technical Implementation Deep Dive: Code & Patterns

Let's move from theory to implementation patterns.

KMP Shared Module: Ktor, SQLDelight, and Serialization

In your KMM Core's commonMain, you would define your data structures and repository.

// In commonMain/src/kotlin/com/induji/shared/data
import kotlinx.serialization.Serializable

@Serializable
data class B2bLead(
    val eventId: String, // UUID generated on client
    val email: String,
    val phone: String,
    val company: String,
    val consent: ConsentData
)

@Serializable
data class ConsentData(
    val contactConsent: Boolean,
    val advertisingConsent: Boolean,
    val timestamp: Long,
    val version: String
)

// In your repository class
suspend fun submitLead(lead: B2bLead) {
    try {
        val response = httpClient.post("https://api.yourdomain.com/v1/leads") {
            contentType(ContentType.Application.Json)
            setBody(lead)
        }
        // Handle successful submission
    } catch (e: Exception) {
        // If network fails, save to SQLDelight
        db.leadQueries.insertLead(lead)
    }
}

This snippet demonstrates using kotlinx.serialization for type-safe data handling and a basic repository pattern that includes an offline-first strategy.

ERP Integration: Event-Driven Architecture

When the lead is qualified in the ERP, your system should publish a message. Using a message queue like Kafka is superior to webhooks for its durability and scalability.

Example Kafka Event Payload (JSON):

{
  "eventId": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
  "eventName": "QualifiedLead",
  "userData": {
    "email": "test@example.com",
    "phone": "+919876543210"
  },
  "customData": {
    "leadValue": 50000,
    "currency": "INR"
  },
  "eventTime": 1678886400,
  "consent": {
      "advertisingConsent": true
  }
}

Building the Secure CAPI Service

This service subscribes to the Kafka topic. Upon receiving a message, it performs the final steps.

A code snippet in Go or Kotlin showing a server-side function that hashes user data using SHA-256 and prepares a JSON payload for the Meta Conversions API.

// Example in Go
func processKafkaMessage(message []byte) {
    var event LeadEvent
    json.Unmarshal(message, &event)

    // 1. Check for consent
    if !event.Consent.AdvertisingConsent {
        log.Printf("Skipping event %s due to lack of consent", event.EventId)
        return
    }

    // 2. Hash PII
    hashedEmail := sha256.Sum256([]byte(event.UserData.Email))
    
    // 3. Construct Meta CAPI Payload
    capiPayload := map[string]interface{}{
        "data": []map[string]interface{}{
            {
                "event_name": "Lead",
                "event_time": event.EventTime,
                "event_id": event.EventId, // Crucial for deduplication
                "user_data": map[string]string{
                    "em": fmt.Sprintf("%x", hashedEmail),
                    // ... other hashed fields
                },
                "custom_data": event.CustomData,
            },
        },
    }
    
    // 4. Send to Meta CAPI via HTTP POST
    sendToMeta(capiPayload)
}

This service is the final, critical gatekeeper, ensuring only consented, hashed, and high-quality data is sent to Meta.

Measuring Success: Beyond ROAS to Predictive LTV

The immediate benefit of this architecture is a dramatic improvement in Meta's algorithmic targeting. By feeding it signals based on qualified leads instead of raw form fills, you teach the platform what a valuable customer profile looks like. This directly leads to:

  • Lower Cost Per Qualified Lead (CPQL): You spend less to acquire leads that actually have business potential.
  • Higher Return on Ad Spend (ROAS): Your ad spend becomes significantly more efficient.

But the true power of this system is realized in the next step. When your ERP marks a deal as "Won" with a contract value of ₹5,00,000, it can publish another event (deal.won). Your CAPI service can then send a Purchase event to Meta with this value. This unlocks Meta's Value-Based Bidding (VBB), allowing you to optimize campaigns not just for leads, but for maximum predicted revenue. You move from optimizing for ROAS to optimizing for Predictive Lifetime Value (pLTV), a paradigm shift in B2B performance marketing.


Frequently Asked Questions (FAQ)

Q1: Why not just use Meta's native Lead Ads forms? Meta's Lead Ads are convenient but offer limited customization, a poor user experience for complex B2B products, and less control over the DPDP consent process. Most importantly, they fire a "Lead" event immediately on submission, polluting your data with unqualified leads and training Meta's algorithm on low-quality signals. Our architecture solves this by only firing the event after internal qualification.

Q2: Can this architecture work with other ad platforms like Google Ads? Absolutely. The core pipeline (App -> ERP -> Event Bus) is platform-agnostic. You would simply create another microservice that subscribes to the same Kafka topic (e.g., lead.qualified) and formats the data for Google's Offline Conversion Import or Enhanced Conversions for Leads, sending it to the appropriate Google Ads API endpoint.

Q3: What's the advantage of Kotlin Multiplatform over React Native or Flutter for this? While React Native and Flutter are excellent frameworks, KMP offers a unique advantage for B2B apps where performance and native fidelity are paramount. KMP allows you to share non-UI logic (the most complex part) while building the UI with the platform's standard, fully native toolkit (SwiftUI/Jetpack Compose). This avoids the "uncanny valley" feel of some cross-platform apps and eliminates any potential performance bottlenecks from a JavaScript bridge (React Native) or a custom rendering engine (Flutter).

Q4: How do we handle event deduplication between the Meta Pixel (if any) and the Conversions API? This architecture is designed for deduplication. The unique event_id is generated in the KMP app. If you also have a Meta Pixel on a thank-you web page, you can pass this same event_id to the Pixel's track call. When Meta receives two events (one from the Pixel, one from CAPI) with the same event_id, it automatically deduplicates them, ensuring each conversion is counted only once.

Q5: What's a realistic timeline for implementing this architecture? For a mid-sized enterprise with an existing modern ERP and a capable engineering team, a phased implementation could look like this:

  • Phase 1 (4-6 weeks): Build the CAPI service and integrate it with your ERP's existing workflows to send server-side events for web-generated leads.
  • Phase 2 (10-14 weeks): Develop the core Kotlin Multiplatform app with the lead capture form and DPDP consent module.
  • Phase 3 (Ongoing): Refine the system, add more conversion events (e.g., Purchase), and integrate with other ad platforms. The total timeline can vary significantly based on the complexity of your ERP and the required app features.

Ready to Build a High-Performance, Compliant B2B Lead Engine?

This architecture is complex but delivers an unparalleled competitive advantage by aligning your marketing signals with real business outcomes, all while embedding data privacy at its core. The team at Induji Technologies specializes in architecting and implementing these next-generation systems, from high-performance Kotlin Multiplatform mobile apps to secure, event-driven data pipelines and complex ERP integrations.

Contact us today for a free architectural consultation and a detailed quote to build your future-proof B2B marketing engine.

Related Articles

Ready to Transform Your Business?

Partner with Induji Technologies to leverage cutting-edge solutions tailored to your unique challenges. Let's build something extraordinary together.

Architecting a DPDP-Native B2B Lead Engine - Kotlin Multiplatform, Meta CAPI & Next-Gen ERP | Induji Technologies Blog