Backend

Architecting a Production Multi-Gateway E-Commerce Platform with Tri-Lingual LTR/RTL Localization

DI
DILSHAD ABDULLA Cloud Author
Architecting a Production Multi-Gateway E-Commerce Platform with Tri-Lingual LTR/RTL Localization

An in-depth engineering case study on handling bi-directional layouts (English LTR vs. Kurdish RTL), concurrent session carts, multi-gateway payments (Stripe, FIB, FastPay, COD), and automated asynchronous PDF invoicing in Python.


πŸ‘¨β€πŸ’» Engineering & System Metadata

  • Designed & Engineered by: Dilshad Abdulla β€” Senior Software Engineer & System Architect
  • Platform: TeachCloud.dev
  • Live Blueprint & Interactive Flowcharts: /ebuyme-sys
  • Technology Stack: Python 3.12 | Flask Blueprints | SQLAlchemy ORM | WeasyPrint Engine | Stripe & FIB APIs | Bi-Directional CSS Grid/Flexbox

⚑ Executive Summary: The Architectural Challenge

When building modern consumer digital storefronts across the Middle East and global markets, three major technical hurdles emerge:
1. Bi-Directional UI/UX: Supporting English (Left-to-Right) along with Sorani and Badini Kurdish (Right-to-Left) without maintaining two separate frontends.
2. Fintech Fragmentation: Handling diverse payment rails simultaneouslyβ€”international credit cards (Stripe), local mobile wallets (First Iraqi Bank, FastPay, ZainCash), and Cash on Delivery (COD).
3. Flash-Sale Concurrency: Preventing overselling and inventory race conditions when hundreds of shoppers checkout the last stock unit simultaneously.

Below is the complete 5-stage architecture and visual flowcharts powering EBuyMe.


πŸ“Š Stage 1: Platform Entry & Multilingual Localization (LTR & RTL)

The entry engine dynamically resolves language preferences from headers or session cookies, flips page orientation (dir="rtl" vs dir="ltr"), and sets localized currency baselines (USD / IQD).

Stage 1: Platform Entry & Multilingual Localization

Key Architectural Concepts:

  • Context Middleware: Uses Flask @app.before_request to detect language parameters and inject locale dictionaries into Jinja2 templates.
  • Bi-Directional CSS: Relies on CSS Logical Properties (margin-inline-start, padding-inline-end) and flex direction switches rather than hardcoded left/right values.

πŸ“Š Stage 2: User Registration & Account Authentication

A zero-trust onboarding pipeline handling input validation, cryptographic password hashing, email token activation, and session security.

Stage 2: User Registration & Authentication Lifecycle

Key Architectural Concepts:

  • Argon2 / bcrypt Hashing: Secures user passwords with adaptive work factor parameters.
  • Timed Token Verification: Issues cryptographic itsdangerous URL-safe tokens for email activation and password resets.
  • Account Lockout Shield: Prevents brute-force credential stuffing with sliding-window failed login attempt tracking.

πŸ“Š Stage 3: Catalog Discovery & Dynamic Mixed Recommendations

Fast product catalog search with multi-attribute facet filtering, stock verification, and dynamic cross-category recommendation engines.

Stage 3: Catalog Discovery & Recommendation Engine

Key Architectural Concepts:

  • Faceted Search: Indexes product attributes (brand, category, price range, color, rating) with composite database indexes.
  • Recommendation Matrix: Blends collaborative filtering and category-affinity scoring to deliver personalized product suggestions.

πŸ“Š Stage 4: Shopping Cart, Multi-Gateway Payment & Automated Invoicing

The central transactional pipeline managing cart persistence, address validation, multi-gateway checkout, row-level inventory locking, and automated PDF invoice generation.

Stage 4: Shopping Cart, Payment & Automated Invoice Generation

πŸ’» Production Code: Atomic Stock Decrement & Webhook Verification

@ecommerce_bp.route("/webhook/payment/verify", methods=["POST"])
def verify_payment_webhook():
    """
    Idempotent payment webhook: verifies HMAC cryptographic signature,
    safely reserves stock under row-level database lock, and dispatches invoice.
    """
    payload = request.get_data()
    signature = request.headers.get("X-Signature")

    # 1. Cryptographic HMAC validation
    if not verify_gateway_hmac(payload, signature):
        abort(400, "Invalid payment signature")

    data = request.get_json()
    order_ref = data.get("order_ref")

    # 2. Atomic Database Transaction with Row-Level Locking
    with db.session.begin():
        order = Order.query.filter_by(reference=order_ref).with_for_update().first()
        if not order or order.status == "PAID":
            return jsonify({"status": "already_processed"}), 200

        # Decrement stock atomically to prevent race conditions
        for item in order.items:
            product = Product.query.filter_by(id=item.product_id).with_for_update().first()
            if product.stock < item.quantity:
                raise InsufficientStockError(f"Item '{product.name}' is out of stock")
            product.stock -= item.quantity

        order.status = "PAID"

    # 3. Asynchronously trigger WeasyPrint PDF receipt & customer email
    generate_and_email_invoice.delay(order.id)
    return jsonify({"status": "success"}), 200

πŸ“Š Stage 5: Executive CMS Order & Logistics Monitoring

Operations control center handling order state machine transitions (Pending βž” Processing βž” Shipped βž” Delivered), courier dispatch assignment, inventory restocking thresholds, and executive business telemetry.

Stage 5: Executive CMS Monitoring & Logistics Control Center


🎬 Real Live Run Simulation: Step-by-Step Order Lifecycle

Here is the actual step-by-step user journey with real production screenshots captured during a live checkout:


Step 1 of 8: Storefront Landing (Before Login)

Visitor arrives at the marketplace before authentication. The template dynamically resolves client locale (English, Sorani Kurdish, or Badini Kurdish), loads trending products, featured departments, and initializes the guest session cart.

Step 1: Storefront Landing


Step 2 of 8: Customer Authentication & Session Login

Customer logs in securely. The authentication module validates credentials using salted hashes, rotates session tokens to prevent session fixation, and synchronizes items from the guest cart into the persistent user profile.

Step 2: Customer Authentication


Step 3 of 8: Live Product Search & Faceted Filtering

Real-time debounced search query executed against product catalog indices. Customers filter results by department (Electronics, Men, Women), brand facets, price ranges, and in-stock inventory status.

Step 3: Live Product Search


Step 4 of 8: Product Detail & "Add to Cart" Action

Customer evaluates high-resolution image galleries, technical specifications, warranty tiers, and variant options (color, storage). Clicking "Add to Cart" sends an AJAX post to update the cart counter dynamically without page reload.

Step 4: Product Detail & Add to Cart


Step 5 of 8: Shopping Cart Review & Order Calculation

Customer reviews items in the shopping cart, adjusts quantities, applies promo coupon codes, and views computed subtotal, delivery fees, and estimated sales tax before proceeding to checkout.

Step 5: Shopping Cart Review


Step 6 of 8: Shipping Address Selection & Entry

Customer selects a previously saved shipping destination or submits a new delivery address with recipient name, phone number, city, and delivery zone notes.

Step 6: Shipping Address Selection


Step 7 of 8: Multi-Gateway Payment & PDF Invoice Dispatch

Payment is completed via chosen gateway (Cash on Delivery / Credit Card / FastPay / ZainCash). The database performs atomic row-level locks, decrements warehouse stock, generates an official PDF invoice, and sends confirmation email.

Step 7: Multi-Gateway Payment & PDF Invoice


Step 8 of 8: Session Termination & Secure Logout

Order is safely finalized. The customer logs out, terminating the session. Cookies are invalidated, security tokens purged, and the visitor is redirected to the clean public storefront.

Step 8: Session Termination & Secure Logout


Explore the Live Interactive Architecture Blueprint

Inspect all 5 interactive flowchart stages, zoomable SVG diagrams, multi-currency pricing, and technical manuals directly on TeachCloud.

πŸš€ Launch EBuyMe Architecture Blueprint & Flowcharts →
LinkedIn
|
| 28 Oct 2026
⚑ Updates
πŸš€ Google Cloud & Workspace (10% Off): Partner with Teach Cloud for hands-on DevOps architecture guides, enterprise solutions, and cloud certifications. β€’ ⚑ Interactive Studios: Test CI/CD workflows, YAML pipelines, and Linux command simulations directly in your browser. β€’ πŸ“¦ Open Architecture: Scalable microservices, SQLite/PostgreSQL optimizations, and production DevOps engineering blueprints. β€’ πŸŽ“ Free Community Access: Explore full interactive tutorials, code sandboxes, and developer quizzes with zero paywalls.