Master Ondc Architecture: A Comprehensive Deep Dive

Featured image for Master Ondc Architecture: A Comprehensive Deep Dive
Spread the love

Master Ondc Architecture: A Comprehensive Deep Dive

Master Ondc Architecture: A Comprehensive Deep Dive

As the open commerce ecosystem gains momentum, senior developers and architects are looking for a practical ondc architecture guide that bridges theory and production‑grade implementation. This article walks you through the core components, design patterns, real‑world case studies, and step‑by‑step workflow that enable you to build, secure, and scale an ONDC‑compliant solution. Whether you are a seasoned engineer, a technical manager, or a product leader, you will find actionable insights, code snippets, and a roadmap that aligns with modern best practices.

Table of Contents

  1. ONDC Architecture Overview
  2. Core Components and Their Interactions
  3. Implementation Workflow & Checklist
  4. Code Examples: From Schema to Integration
  5. Security, Performance, and Scalability
  6. Real‑World Case Studies
  7. Expert Opinion
  8. FAQ
  9. Latest Developments & Tech News
  10. Related Reading from the Developer Community
  11. Recommended Courses & Learning Resources
  12. Conclusion

ONDC Architecture Overview

The Open Network for Digital Commerce (ONDC) is a network‑level protocol that abstracts the buyer‑seller interaction into a set of interoperable services. At its heart, ONDC defines a set of standardised APIs (search, order, fulfillment, billing, etc.) and a registry‑based discovery mechanism. The architecture is deliberately layered to allow participants—retailers, logistics providers, payment gateways—to plug in their own implementations while still speaking a common language.

Why a Layered Approach?

Layering brings three critical benefits:

  • Technology agnosticism: Participants can use Java, Node.js, Go, or any language that can expose HTTP/HTTPS endpoints.
  • Incremental adoption: A retailer can start with the search API and later add order and fulfillment without a wholesale rewrite.
  • Governance and compliance: Centralised policy enforcement (e.g., GDPR, PCI‑DSS) can be applied at the gateway layer, keeping downstream services lightweight.

Core Components and Their Interactions

Figure 1 (conceptual) illustrates the primary building blocks of the ONDC ecosystem. The diagram is omitted for brevity, but the textual description below captures the same information.

1. Registry & Discovery Service

The registry maintains a catalogue of all participating network participants. Each participant publishes a subscriberId and a set of callback URLs for the APIs it supports. The discovery service resolves buyer‑side requests to the appropriate seller endpoints based on geography, latency, or business rules.

2. Gateway (BAP/BPP)

Buyer‑App Providers (BAP) and Seller‑App Providers (BPP) are the front‑ends that translate user actions into ONDC API calls. They act as adapters that:

  • Validate request payloads against the ONDC schema.
  • Enrich payloads with authentication tokens (OAuth2, JWT).
  • Perform fallback routing if a primary seller is unavailable.

3. Core API Services

The protocol defines six core services:

  1. Search: Query the catalogue across multiple sellers.
  2. Select: Choose a concrete offering (SKU, price, availability).
  3. Init: Initialize a transaction, reserve inventory.
  4. Confirm: Confirm order details and lock payment.
  5. Status: Poll order status throughout fulfillment.
  6. Cancel: Revoke an order before fulfillment.

Each service follows a request/response pattern with JSON‑LD payloads that embed context URIs for semantic interoperability.

4. Supporting Services

Beyond the core, the architecture includes:

  • Authentication & Authorization Service (AAAS): Centralised OAuth2 server issuing short‑lived access tokens.
  • Analytics & Auditing Service: Captures immutable logs for dispute resolution.
  • Payment Bridge: Normalises diverse payment providers into a single payment‑mode API.
  • Logistics Orchestrator: Provides real‑time tracking and route optimisation.

Implementation Workflow & Checklist

Transitioning from concept to production requires a disciplined approach. The following checklist is organised by development phases.

Phase 1 – Discovery & Planning

  1. Identify business objectives (e.g., B2B ordering, marketplace expansion).
  2. Map existing services to ONDC core APIs – note gaps.
  3. Select technology stack (Node.js/Express, Spring Boot, Go‑Gin, etc.).
  4. Define SLA targets (latency < 200 ms, 99.9 % availability).
  5. Register a subscriberId with the ONDC registry sandbox.

Phase 2 – Core API Development

  1. Implement JSON‑LD schema validation using libraries such as ajv (Node) or json-schema-validator (Java).
  2. Develop the /search endpoint – include pagination, filtering, and sorting.
    // Example: Express.js search endpoint
    const express = require('express');
    const router = express.Router();
    const Ajv = require('ajv');
    const ajv = new Ajv();
    const searchSchema = require('./schemas/search-schema.json');
    
    router.post('/search', async (req, res) => {
      const valid = ajv.validate(searchSchema, req.body);
      if (!valid) return res.status(400).json({error: ajv.errors});
      // Business logic – query product DB
      const results = await productService.search(req.body.context, req.body.message);
      res.json({context: req.body.context, message: {catalog: results}});
    });
    module.exports = router;
  3. Secure each endpoint with JWT verification against the AAAS public keys.
  4. Instrument logging with correlation IDs for end‑to‑end traceability.

Phase 3 – Integration & Testing

  1. Deploy a sandbox gateway that mimics a BAP.
    {
      "subscriberId": "my-retailer-123",
      "callbackUrls": {
        "search": "https://api.myretailer.com/ondc/search",
        "order": "https://api.myretailer.com/ondc/order"
      },
      "domains": ["retail", "b2b"]
    }
  2. Run contract tests using pact or postman collections supplied by ONDC.
  3. Perform load testing (e.g., k6) targeting 5 000 concurrent search requests.
  4. Validate compliance with the ONDC certification suite – pass all mandatory checks.

Phase 4 – Productionisation

  1. Deploy to a Kubernetes cluster with auto‑scaling based on CPU and request latency.
  2. Enable mutual TLS between gateway and core services.
  3. Configure a CDN edge‑cache for static catalogue data (TTL = 5 min).
  4. Establish a monitoring dashboard (Prometheus + Grafana) showing request rates, error ratios, and SLA breaches.

Code Examples: From Schema to Integration

Below are two concrete snippets that illustrate the most common integration points.

Example 1 – ONDC Search Request Payload (JSON‑LD)

{
  "@context": "https://schema.org/",
  "message": {
    "intent": {
      "type": "search",
      "item": {
        "descriptor": {
          "name": "Industrial Drill",
          "code": "IND-DRL-001"
        }
      }
    },
    "criteria": {
      "price": {"range": {"min": 5000, "max": 15000}},
      "location": {"city": "Bengaluru"}
    }
  },
  "context": {
    "domain": "retail",
    "action": "search",
    "country": "IN",
    "city": "Bengaluru",
    "bap_id": "bap.mycompany.com",
    "bap_uri": "https://bap.mycompany.com",
    "transaction_id": "txn-9a8b7c6d",
    "timestamp": "2024-09-15T12:34:56Z"
  }
}

This payload can be sent directly from a BAP to any registered BPP that supports the search API.

Example 2 – Node.js Order Confirmation Handler

// orderConfirm.js – Handles /confirm callback from a buyer
const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const {verifyToken} = require('../utils/auth');

router.post('/confirm', async (req, res) => {
  // Verify JWT from the AAAS
  const token = req.headers.authorization?.split(' ')[1];
  try {
    await verifyToken(token);
  } catch (e) {
    return res.status(401).json({error: 'Invalid token'});
  }

  const {context, message} = req.body;
  // Persist order to DB
  const order = await Order.create({
    transactionId: context.transaction_id,
    buyerId: context.bap_id,
    sellerId: context.bpp_id,
    items: message.order.item,
    total: message.order.price.total,
    status: 'CONFIRMED'
  });

  // Respond with ACK per ONDC spec
  res.json({
    context: {
      ...context,
      action: 'confirm',
      message_id: 'msg-' + Date.now()
    },
    message: {order: {id: order.id, status: 'CONFIRMED'}}
  });
});
module.exports = router;

Security, Performance, and Scalability

Implementing a robust ondc architecture is not just about functional compliance; it also demands a security‑first mindset and performance engineering.

Authentication & Authorization

  • OAuth2 with JWT: ONDC requires short‑lived access tokens signed by the AAAS. Validate the kid header against the JWKS endpoint.
  • Scope‑based access: Restrict each participant to the APIs they are authorised for (e.g., a logistics provider should only receive status callbacks).
  • Mutual TLS for intra‑service communication adds a second layer of trust.

Data Validation & Sanitisation

All inbound JSON‑LD must be validated against the official schema. Reject any payload with unknown fields to mitigate injection attacks.

Performance Optimisations

  • Edge caching of catalogue data reduces latency for repeat searches.
  • Read‑through cache (Redis) for inventory look‑ups to avoid DB hot‑spots.
  • Asynchronous processing for long‑running tasks (e.g., payment settlement) using message queues like RabbitMQ or Kafka.
  • Rate limiting at the gateway – 100 requests per second per subscriber to protect downstream services.

Scalability Patterns

Adopt the following patterns for horizontal scaling:

  • Stateless microservices: Keep services stateless; store session data in Redis or a distributed cache.
  • Service mesh (e.g., Istio): Provides observability, traffic shaping, and security policies without code changes.
  • Event‑driven architecture: Emit domain events (order‑created, payment‑captured) to decouple BPPs and logistics partners.

Real‑World Case Studies

Below are three anonymised case studies that illustrate how organisations have successfully adopted the ONDC model.

Case Study 1 – B2B Procurement Platform

Context: A mid‑size manufacturing firm needed a single pane‑of‑glass to source raw materials from dozens of suppliers.Solution: The team built a BAP using React + Node.js, integrated with the ONDC search and order APIs, and onboarded five key

1. Architectural Foundations and System Design

When implementing robust solutions for ondc architecture, system architects must focus on structural durability, low latency, and decoupled designs. In projects involving ONDC architecture, a modular design pattern is highly advantageous. This approach allows developers to isolate components, scale them independently, and optimize resource usage based on real-time request patterns. Using asynchronous messaging queues (such as RabbitMQ, Celery, or Apache Kafka) can offload intense tasks from the primary request thread, thereby ensuring high availability and protecting the system from cascading service failures.

Furthermore, the database layer must be designed with transaction safety, connection pooling, and replication in mind. Using read replicas can significantly reduce the load on the master node during heavy traffic spikes. Implementing an API gateway enables clean traffic routing, rate limiting, request validation, and unified security policies. This unified layout simplifies operational maintenance and speeds up troubleshooting workflows for technical teams.

2. Security Hardening and Threat Mitigation

Security is a paramount concern for any application operating with ondc architecture. Adhering to the principle of least privilege, access controls should be strictly limited across all components. For deployments related to ONDC architecture, sensitive variables (such as database passwords, third-party API credentials, and TLS certificates) should never be stored directly in the source code or deployment scripts. Instead, they should be managed via cloud-native secrets managers (like AWS Secrets Manager, HashiCorp Vault, or Google Cloud Secret Manager) and loaded securely at runtime.

To secure the data layer, all external communication channels must be encrypted with modern TLS protocols. Input parameters should undergo rigorous validation and sanitization at the API gateway layer to prevent SQL injection, cross-site scripting (XSS), and malicious parameter tampering. Regular dependency vulnerability scanning (using tools like Snyk, Dependabot, or Bandit) should be integrated into the deployment pipeline to identify and remediate vulnerable packages early in the release cycle.

3. Scaling Strategies and Performance Optimization

Minimizing application latency and maximizing throughput are key indicators of a successful ondc architecture rollout. For systems executing workflows for ONDC architecture, adopting a multi-tiered caching structure yields immediate performance gains. Tools like Redis or Memcached can store frequently accessed database queries, transient session variables, and parsed system configurations. This relieves pressure on back-end databases and decreases API response times to the low millisecond range.

In addition, using reverse proxies (such as Nginx or HAProxy) and Content Delivery Networks (CDNs) helps distribute request loads geographically and serve static assets with minimal delay. Autoscale rules (such as Horizontal Pod Autoscaling in Kubernetes or VM scale sets in cloud environments) should be defined using CPU, memory, and custom message queue length metrics to align compute resources with real-time user activity, optimizing hosting expenditures.

4. Observability, Logging, and Real-Time Monitoring

Sustaining visibility is crucial when orchestrating processes related to ondc architecture. To ensure the reliability of systems running ONDC architecture, developers must deploy comprehensive logging, trace collection, and system metrics tracking. Logs should be structured as structured JSON objects, making it easier for central log ingestion tools (like Grafana Loki, the Elastic Stack, or Splunk) to parse, index, and query log entries for rapid diagnosis of failures.

Dashboard visualizations (e.g., using Grafana or Datadog) should display critical golden signals: latency, traffic, error rates, and resource saturation. Implementing distributed tracing using frameworks like OpenTelemetry or Jaeger allows engineers to track the lifecycle of a request as it crosses service boundaries, pinpointing latency bottlenecks in network calls or database execution. Automatic alerting rules should trigger notifications via PagerDuty or Slack when anomalies arise.

Scroll to Top