Modernized a Trading App for a Riyadh-Based Brokerage Firm to Reduce Order Processing Delays by 42%

Trading app screens: markets, portfolio and order details

Project Overview

Our client wanted to modernize its mobile trading app. The app became slow when many people were buying and selling shares at the same time. Order updates came late, and screens took too long to load. The Riyadh-based brokerage firm wanted to fix this without replacing its main order system (OMS) and without stopping trading.

The main objective was to build a fast and reliable trading app backend with live order status updates, safe order retry, real-time price streaming and order tracking tools, while keeping the existing OMS as the final authority on every order.

Our development team rebuilt the app's backend in small parts, using a Kafka event pipeline and WebSocket connections to send live updates. Because we changed the system in stages, trading kept running the whole time. The app fits the needs of brokerage customers in Saudi Arabia.

Business Challenges

  • Polling amplified backend load

    The app fetched order statuses by calling the backend repeatedly. Request volume grew with open orders multiplied by active sessions, so load peaked exactly when markets were busiest.

  • Ambiguous submission outcomes

    When a connection dropped after an order left the device, the app could not distinguish a rejected order from an unacknowledged one. Users retried manually, creating duplicate order risk.

  • Quote and portfolio fan out

    A single portfolio screen triggered several dependent calls for holdings, balances, prices and transactions. Watching several securities multiplied that traffic.

  • Fragmented diagnostics

    Logs had no shared request identifier, so tracing one order from the app to the OMS meant matching timestamps by hand.

Our Solution

An API gateway became the single entry point for the mobile client, with Node.js services behind it for authentication, orders, portfolios, accounts and market data.

  • REST endpoints for order placement, modification, cancellation, portfolio retrieval and account queries
  • JSON schema validation at the gateway with a uniform error envelope and machine-readable error codes
  • Per-service timeouts, retries with exponential backoff and jitter on idempotent calls only, and circuit breakers on OMS-facing routes
  • Token bucket rate limiting per user and per client application
  • Independent deployment of each service

An integration adapter translates between the OMS's native message formats and a clean internal domain model, so legacy behavior does not leak into the new services.

  • Order states are modeled as a finite state machine: pending submission, acknowledged, partially filled, filled, cancel requested, cancelled and rejected, with only legal transitions accepted.
  • Topics partitioned by order identifier so events for one order are processed in sequence.
  • Separate consumer groups for app notifications and audit persistence, so a slow consumer never blocks the other.
  • Event identifiers, order references, monotonically increasing sequence numbers, and OMS timestamps on every event, enabling duplicate discard and gap detection
  • Dead letter topics with alerting and a controlled replay path.

  • The client generates a UUID idempotency key per order intent
  • The key, a hash of the request body and the submission state, are written in the same transaction as the order record, protected by a unique constraint
  • A retry with a known key returns the stored state, and the same key with a different payload is rejected as a conflict
  • Orders that time out toward the OMS enter an unconfirmed state and a reconciliation queue with bounded polling
  • The app shows "awaiting confirmation" and disables resubmission until the state resolves

  • WebSocket channels with per session subscription management
  • Snapshot plus delta protocol with sequence numbers, heartbeat frames and resubscription from the last seen sequence after reconnect
  • Redis cache aside reads with short TTLs for reference data and recent quotes
  • Server-side backpressure that drops superseded quotes for slow clients
  • Execution paths read from the OMS, never from cached quotes

  • Composite responses shaped per mobile screen
  • Composite indexes and EXPLAIN ANALYZE review of the heaviest queries
  • Materialized views for end-of-day position summaries
  • Keyset pagination replacing offset pagination for transaction history
  • RDS read replicas for reporting queries and explicit cache invalidation on order events

  • Correlation identifiers propagated through gateway headers, service logs, Kafka message headers and adapter calls
  • OpenTelemetry tracing and structured JSON logs
  • Dashboards for p50, p95 and p99 latency, consumer lag, WebSocket connection counts and OMS round trip time
  • Append-only audit records for order actions and account changes
Trading app order ticket awaiting confirmation and the live order status timeline
Trading operations dashboard on a laptop cycling through the results: order status delay, duplicate submissions, quote caching and portfolio load time

Technology Stack

  • Mobile

    React Native

    One codebase for iOS and Android with native performance for order entry

  • Backend

    Node.js, REST

    Non-blocking I/O suits many concurrent, short lived requests

  • API management

    AWS API Gateway

    Central authentication, validation and throttling

  • Event streaming

    Apache Kafka

    Partitioned ordering, replay and independent consumer groups

  • Live delivery

    WebSockets

    Removes repeated polling for quotes and order updates

  • Cache

    Redis

    Low-latency reads and a shared subscription registry

  • Database

    PostgreSQL with read replicas

    Transactional integrity for orders and audit data

  • Cloud

    AWS EC2, RDS, CloudWatch

    Managed databases and centralized monitoring

  • Authentication

    OAuth 2.0

    Short-lived tokens with refresh token rotation

  • Observability

    OpenTelemetry, structured logs

    End-to-end request tracing

Saudi Specific Integrations

  • Saudi Exchange (Tadawul) market data

    Quotes and reference data normalized through the adapter, with trading sessions handled on the Sunday to Thursday calendar and opening and closing auction periods

  • Nafath identity verification

    National digital identity support for onboarding and sensitive actions

  • Arabic and RTL support

    Bilingual interface, Arabic and English instrument names and Hijri and Gregorian date display

  • Regulatory alignment

    Audit trails and order records designed around Capital Market Authority (CMA) recordkeeping expectations

  • Data protection

    Handling of personal and financial data aligned with the Personal Data Protection Law (PDPL), including field-level log redaction

  • Local funding flows

    Integration points for Saudi bank transfers and SADAD-supported payments

Development Process

  1. Assessment

    Mapped API dependencies, the order lifecycle, database access patterns and OMS touchpoints.

  2. Service extraction

    Choose workflows that could move into standalone services without touching the trading engine, following the strangler fig pattern.

  3. Route by route cutover

    Placed new endpoints behind the gateway and shifted traffic using feature flags and weighted routing.

  4. Shadow comparison

    Mirrored requests to old and new paths and compared responses, with contract tests catching schema drift.

  5. Performance validation

    Replayed recorded auction period traffic, ran load tests until p99 crossed the service level objective, and ran soak tests that exposed connection leaks in the WebSocket tier. Profiling led to PgBouncer-style connection pooling, leaner payloads and optimistic locking with a version column on order records.

  6. Failure injection

    Simulated OMS slowness, dropped Kafka brokers and mobile network loss to confirm circuit breakers, reconciliation and reconnection behaved as designed.

  7. Canary release and decommissioning

    Exposed each workflow to a small share of users first, then retired legacy components only after clean production runs.

Measurable Results

  • Order processing delays reduced by 42%, with median order status delay at peak improving from about 1.1 seconds to about 640 milliseconds.

  • Duplicate order submissions down 96%, from about 1.4% of peak session submissions to under 0.06%.

  • Backend quote request volume reduced by 71%, with Redis serving about 88% of reference and quote lookups.

  • Portfolio screen load time at p95 cut from 3.1 seconds to 1.2 seconds. Calls per screen reduced from 6 to 1.

  • Mean time to diagnose order incidents cut from about 45 minutes to under 8 minutes.

  • Release cadence moved from one full release every 4 to 6 weeks to independent service releases several times a week, with regression scope per release reduced by roughly 70%.

Modernize Your Trading Platform Now!

If your trading application struggles with delayed order states, uncertain submissions, or quote traffic that competes with order flow, our engineering team can assess your architecture and outline a migration path that leaves your core trading system untouched.

Get a Free Quote
Contact Us

Ready To Fuel Your Vision With AI-Powered Innovation?

Our Presence

Level- 18, Dubai World Trade Centre Tower, Sheikh Rashid Tower, Sheikh Zayed Rd, Dubai, UAE

business@code-brew.com +971-55-645-7972

Plot no I - 36, Sector 83 Alpha, Mohali SAS Nagar 140308

business@code-brew.com +91-771-976-8427

Al Akaria 2, 6926 Olaya Street, RHOA2566, Riyadh, Saudi Arabia.

business@code-brew.com

Av. Miguel Hidalgo y Costilla 1995, Arcos Vallarta, 44600 Guadalajara, Mexico

business@code-brew.com +1(213)2614953

4231 Balboa Ave #512 San Diego, CA 92117 United States

business@code-brew.com +1(213)2614953

2nd floor, College House, 17 King Edwards Rd, London HA4 7AE, UK

business@code-brew.com +44 (20) 82644493

Partner With Experts Who Leverage AI & Tech To Transform Ideas Into Market-Leading Solutions.

Wait! Looking for Right Technology Partner For Your Business Growth?

It's Time To Convert Your Business Idea Into Success!

Get Free Consultation From Top Industry Experts:
gif
I would like to keep it to myself