PRODUCTION APPLICATION · INSTITUTIONAL CASE OPERATIONS
Financial Desk · Multi-Tenant Case Platform & Gateway
An institutional B2B case-operations platform and API gateway serving commercial banks and Non-Banking Financial Companies (NBFCs). Built with a Rust/Leptos WebAssembly frontend and an asynchronous FastAPI gateway that dynamically isolates tenant context per request using Python ContextVar primitives, routing authenticated dispute workflows to upstream Frappe ERP systems without maintaining a redundant local database.
ROLE & OWNERSHIPSoftware Engineer · IO2iFrontend Client & BFF Gateway
FRONTEND ENGINERust + Leptos (WASM)CSR WebAssembly Client
ISOLATION MODELContextVar ScopeHost-Based Dynamic Auth
CORE DATA STOREUpstream Frappe ODRStateless BFF Architecture
Figure 1: Financial Desk portfolio dashboard displaying active dispute cases, stage distribution, advocate allocations, and hearing milestones for an institutional tenant.
02. THE OPERATIONAL PROBLEM
Managing High-Volume Institutional Arbitration Across Competing Lenders
IO2i provides dispute resolution and arbitration management operations to commercial banks and NBFCs across India. In high-volume dispute operations, institutional legal teams manage large caseloads and require structured operational visibility across the entire dispute lifecycle: intake schedules, physical notice dispatch tracking, arbitrator appointment, hearing sessions, and certified award uploads.
Financial Desk was designed to resolve several key operational and architectural challenges in dispute management:
- Centralized Case Management: Legal operations teams handling multiple dispute portfolios require a structured interface for case lifecycles rather than fragmented file transfers and manual tracking sheets.
- Automated Document Generation: Preparing dispute notices and legal claims manually introduces data transcription errors across arbitrator names, loan account numbers (LANs), and claim figures.
- Unified Case Visibility: Operations teams require a consolidated interface to inspect notice delivery progress, advocate assignments, hearing schedules, and certified award documents.
- Strict Multi-Tenant Isolation: Commercial lenders operate competing portfolios under strict confidentiality agreements. Institution A must never view, query, or infer claims, borrower identities, arbitrator allocations, or counsel rosters belonging to Institution B.
Deploying dedicated server instances and independent database clusters for every client increases infrastructure cost and operational maintenance overhead. Conversely, a shared database relying solely on manual WHERE tenant_id = ... query filters introduces significant risk of cross-tenant data leaks if a filter condition is accidentally omitted.
03. WHAT I BUILT & SYSTEM BOUNDARIES
Full-Stack Case-Operations Client & Tenant-Aware Gateway
I built the frontend client and the backend gateway service for Financial Desk from scratch, establishing a clear separation between our delivery platform and upstream business systems:
WHAT I PERSONALLY BUILT- Rust/Leptos WebAssembly frontend SPA (CSR) with zero-cost reactive signals.
- FastAPI Backend-for-Frontend (BFF) proxy gateway with request-scoped tenant routing.
- Dynamic tenant resolution middleware using Python
ContextVar. - Asynchronous central authority sync validating tenant credentials via HMAC-SHA256.
- Case management workflows: multi-facet filtering, detail views, advocate reassignment.
- Security layer: strict HTTP headers, CORS dynamic allowlists, and anti-enumeration.
- Docker multi-container deployment, Nginx proxy, and Prometheus observability metrics.
UPSTREAM SYSTEM BOUNDARIES- Frappe ERP Core: Upstream system of record storing master dispute dockets.
- Isolated Data Stores: Upstream MariaDB/PostgreSQL databases managed by Frappe.
- Business Logic Methods: Upstream Python endpoints handling case status transitions.
- Notice Delivery Channels: External postal and messaging delivery infrastructure.
- No Local Database: Financial Desk owns zero database rows; it is an authenticated proxy.
Implemented Case-Operations Workflows
DOCKET LISTING & MULTI-FACET FILTERINGReal-time docket querying by case status, loan account number, advocate, and hearing date range without page reloads.
ADVOCATE ALLOCATION & REASSIGNMENTWorkflows to assign panel advocates to contested case batches and transfer matters between legal counsel with audit notes.
BULK DISPATCH CAMPAIGN TRACKINGMonitoring batch legal notice dispatches across Speed Post, WhatsApp, and registered email with live delivery logs.
HEARING TIMELINES & DOCUMENT UPLOADSChronological arbitration event timelines, virtual hearing links, and certified signed document uploads proxied upstream.
04. ARCHITECTURE & DATA FLOW
End-to-End Request Flow: Leptos, Nginx, FastAPI & Upstream Frappe
Financial Desk operates as a stateless proxy gateway. The incoming domain identifies the tenant, the gateway dynamically injects the tenant's distinct API keys, and the upstream Frappe ERP executes queries strictly within that institution's database boundary:
REQUEST LIFECYCLE & TENANT ISOLATION FLOW:
[ Institutional Browser Client (e.g. bank-a.firmportal.in) ]
│
▼ (HTTPS Request)
┌────────────────────────────────────────────────────────────────────────┐
│ NGINX Edge Reverse Proxy (TLS Termination) │
│ • Serves compiled Rust/Leptos WebAssembly SPA bundle (CSR) │
│ • Enforces client_max_body_size and passes X-Forwarded-Host header │
│ • Proxies /api/* requests to internal Uvicorn ASGI socket │
└────────────────────────────────────────────────────────────────────────┘
│
▼ (Internal HTTP)
┌────────────────────────────────────────────────────────────────────────┐
│ FastAPI Gateway Service (Python 3.12 / AsyncIO) │
│ 1. Logging Middleware: Injects X-Request-ID (UUID4) for tracing │
│ 2. Security Headers: Applies CSP, HSTS, X-Frame-Options: DENY │
│ 3. Tenant Middleware: │
│ • Resolves hostname via in-memory _tenant_by_host cache │
│ • Sets ContextVar: _current_tenant.set(tenant_config) │
│ 4. Session Middleware: Validates HMAC-signed bearer session token │
│ 5. API Client (lwt_api_client.py): │
│ • Reads current_tenant ContextVar │
│ • Signs outbound request with tenant.api_key & tenant.api_secret │
└────────────────────────────────────────────────────────────────────────┘
│
▼ (Outbound HTTPS with Tenant Token)
┌────────────────────────────────────────────────────────────────────────┐
│ Upstream Frappe ODR Core Services │
│ • Authenticates tenant API key/secret │
│ • Executes queries against isolated MariaDB/PostgreSQL database │
│ • Enforces business workflows and returns JSON case records │
└────────────────────────────────────────────────────────────────────────┘Why Rust and Leptos for an Institutional Frontend?
When legal coordinators review extensive dispute dockets across multiple legal metadata fields, client applications handling large tabular datasets benefit significantly from predictable rendering performance and low client-side resource overhead during rapid multi-facet filtering.
By compiling the frontend with Rust and the Leptos framework to WebAssembly, the client manipulates tabular DOM state directly with fine-grained reactive signals and zero JavaScript runtime exceptions. Client-side memory usage remains steady regardless of table pagination depth.
05. ENGINEERING DEEP DIVES
Implementation Decisions Backed by Source Code
1. Coroutine-Scoped Multi-Tenancy with Python ContextVar
In asynchronous Python frameworks like FastAPI, traditional thread-local storage (threading.local) is unsafe because multiple coroutines executing concurrent requests share the same OS thread across asynchronous event loop context switches.
I used Python's native contextvars.ContextVar to bind the resolved TenantConfig strictly to the coroutine context of the incoming request. When the request terminates, the context token is cleanly reset, guaranteeing zero cross-tenant credential leakage across concurrent coroutines:
Sanitized Source Excerpt: tenant_registry.py & main.py
from contextvars import ContextVar
from dataclasses import dataclass
from fastapi import Request, HTTPException
from fastapi.responses import JSONResponse
@dataclass(frozen=True)
class TenantConfig:
host: str
tenant_code: str
lwt_base_url: str
api_key: str
api_secret: str
bulk_base_url: str
bulk_api_key: str
# ContextVar scoped strictly to the current asynchronous coroutine
_current_tenant: ContextVar[TenantConfig | None] = ContextVar("current_tenant", default=None)
@app.middleware("http")
async def bind_tenant_context(request: Request, call_next):
# Exclude non-tenant endpoints
if request.url.path in {"/health", "/metrics", "/docs", "/openapi.json"}:
return await call_next(request)
try:
tenant = await resolve_request_tenant(request)
except HTTPException as exc:
return JSONResponse(status_code=exc.status_code, content={"detail": exc.detail})
request.state.tenant = tenant
token = _current_tenant.set(tenant)
try:
response = await call_next(request)
return response
finally:
# Guarantee cleanup even on unhandled exceptions
_current_tenant.reset(token)2. In-Memory Tenant Registry with HMAC-Signed Central Authority Sync
Instead of querying a database on every inbound HTTP request to look up tenant API credentials, the gateway maintains an in-memory dictionary cache (_tenant_by_host) refreshed by a background asyncio loop.
To ensure tenant configurations cannot be tampered with or spoofed, communication with the central authority endpoint is cryptographically verified using HMAC-SHA256 request signatures and response verification:
Sanitized Source Excerpt: tenant_registry.py
import hmac, hashlib, socket, time, json
def _request_signature(timestamp: str) -> str:
message = f"{timestamp}:GET:{_central_url()}:{socket.gethostname()}"
return hmac.new(_central_secret().encode(), message.encode(), hashlib.sha256).hexdigest()
async def refresh_tenant_registry() -> None:
ts = str(int(time.time()))
headers = {
"x-timestamp": ts,
"x-signature": _request_signature(ts),
"x-host-node": socket.gethostname(),
}
async with httpx.AsyncClient(timeout=10.0) as client:
resp = await client.get(_central_url(), headers=headers)
resp.raise_for_status()
payload = resp.json()
# Atomically swap in-memory tenant registry
new_registry = { _normalize_host(row["host"]): _coalesce_tenant_row(row) for row in payload["tenants"] }
global _tenant_by_host
_tenant_by_host = new_registry3. Horizontal Authorization & Anti-Enumeration Hardening
During the migration from individual borrower access to institutional multi-case management, authorization shifted from vertical single-LAN locking to horizontal tenant boundary enforcement.
As documented in our architecture migration notes, we removed hardcoded single-LAN locks and enforced horizontal tenant boundaries upstream. Additionally, to defeat user-enumeration attacks against banking authentication endpoints, all user lookup failures were normalized from HTTP 404 “User not found” to a generic HTTP 403 “Check your email or user ID and try again”, preventing attackers from probing valid bank staff credentials.
06. ENGINEERING CHALLENGES & MITIGATIONS
Observed Technical Constraints & How They Were Resolved
COROUTINE CONTEXT PROPAGATION IN ASYNCHRONOUS TASKSTechnical Constraint: In asynchronous Python, coroutines scheduled outside the primary request flow (such as detached background tasks or helper routines) do not automatically inherit ContextVar state across execution boundaries unless explicitly copied. If tenant context is lost, upstream authenticated calls fail or lose tenancy boundaries.
Implementation: Context boundaries are preserved by capturing context snapshots via contextvars.copy_context().run(worker_fn), ensuring background routines execute within the verified caller tenant boundary.
MANDATORY PRODUCTION SECRETS ENFORCEMENTDifficulty: During containerized deployments, missing or default session secrets in environment variables risked allowing unauthenticated token forgery in staging or production environments.
Mitigation: Implemented strict startup validation in session_auth.py. If SESSION_SECRET is not explicitly set in a non-development environment, the application raises a fatal RuntimeError on startup, preventing misconfigured containers from ever passing health checks.
07. DEPLOYMENT, OBSERVABILITY & OPERATIONS
Containerized Delivery & Telemetry
Financial Desk is packaged as a multi-container Docker Compose deployment managed behind an Nginx reverse proxy on Linux hosts:
NGINX REVERSE PROXYTerminates TLS, enforces body size limits, routes dynamic custom domains, and serves static compiled Leptos WASM assets.
STRUCTURED OBSERVABILITYASGI middleware generates a UUID request correlation ID per request, logging structured JSON logs to stdout with latency timings.
HEALTH & METRICS PROBES/health reports version, tenant count, and registry sync status. Prometheus metrics are exposed at /metrics.
08. LIMITATIONS & LESSONS LEARNED
Architectural Trade-Offs & Next Iterations
- Gateway Proxy Latency Penalty: Because Financial Desk functions as an authenticated proxy rather than maintaining local database tables, queries incur a network hop overhead to upstream Frappe ERP endpoints. We accepted this overhead to maintain strict data isolation and eliminate database schema drift across institutional clients.
- Upstream Endpoint Concurrency Limits: When operations personnel execute broad searches across unindexed dispute records simultaneously, upstream Frappe workers can experience connection saturation.
- Future Defense-in-Depth: If local caching or dedicated operational databases are introduced in the next iteration, I would implement PostgreSQL Row-Level Security (RLS) (
SET LOCAL app.current_tenant = ...) alongside application ContextVars to ensure database-level enforcement.
09. VERIFIED EVIDENCE & CONFIDENTIALITY BOUNDARY
CONFIDENTIALITY STATEMENT:Financial Desk is an internal B2B enterprise platform serving commercial banking and lending institutions. In compliance with institutional confidentiality obligations, client identities, internal domain names, and borrower case records are withheld. All architectural flows, code patterns, and configuration details presented above are verified against actual source code in the repository.