Skip to content

System Architecture & Data Flow

About This Page

What: System boundaries and tech stack, layered relationships among 32 microservices, database architecture and sync pipelines, inter-service communication protocols and latency analysis, the full path a Deposit/Withdrawal takes from initiation to completion (which services and tables it touches), Bank Statement collection frequencies, request tracing examples, monitoring and alerting, and common latency bottlenecks with troubleshooting approaches Audience: Product managers and Operations staff who need to understand the full technical landscape Prerequisites: Getting StartedReading time: 12 minutes Owner: Deposit & Withdrawal Product Team

Key takeaway: The system comprises 32 microservices organized into three tiers — a PHP business logic layer, a Go/Python bank integration layer, and a Python SBA Orchestration layer. Understanding these tiers is the key to locating issues and assessing the impact of changes.


Tech Stack Overview

TierTechnologyComponentsPM Focus
Business LogicPHP/Lumen 5.5Deposit (deposit/), Withdrawal (withdraw/), Bank Card (bankcard_service/), Cash (cash/)Core business APIs, latency-sensitive — directly affects App response time
Bank IntegrationGo + Python hybridGo: BOCHK statements, CGB FPS, SCB, blacklist/whitelist, Airstar gateway; Python: SBA Orchestration, HSBC, ICBC, CMB, CMBCMulti-language heterogeneous bank Channels — you need to check the right language stack's logs when troubleshooting
CommunicationProtobuf RPC + HTTP RESTSRPC (internal sync), HTTP (CRM/external), SM2 Socket (CMB/CMBC)SRPC timeout → individual Deposit/Withdrawal stuck; HTTP timeout → CRM operation failure
Bank ProtocolsB2E XML / MT910 / SFTP+GPG / SM2 encryption / REST APIOne protocol per bankDifferent protocols determine Bank Statement retrieval speed and automation level
StorageMySQL (sharded) + Elasticsearch (Canal sync) + RedisPrimary DB sharded into 100 tables, ES full-text search, Redis cache + locksCRM search uses ES (second-level latency), not direct database queries
MessagingRedis event queues + RabbitMQInternal async events + cross-service decouplingQueue backlog → batch Deposit/Withdrawal delays

32 Microservices by Category

Full Service Inventory

Core Business (4)

ServiceLanguagePortResponsibilityExternal Interface
deposit/PHP20001Deposit applications, Bank Statements, Matching, Approval, in-transit funds, reconciliationSRPC + HTTP REST
withdraw/PHP20002Withdrawal applications, 3-step Approval (Audit → Confirm → Remittance), bank ChannelsSRPC + HTTP REST
cash/PHP20003Cash service API and batch processingHTTP REST
bankcard_service/PHP20005Full Bank Card lifecycle management (binding/verification/unbinding)HTTP REST

Bank Integration Layer (13)

ServiceLanguageBankResponsibilityCommunicationCall Direction
bochk_flow_go/GoBOCHKB2E protocol parsing, statement conversionB2E XMLmoomoo → Bank (active pull)
bochk_deposit_mgr/PythonBOCHKDeposit Orchestration managementSRPCInternal call
bochk_fts_mgr/PythonBOCHKFTS (remittance) managementSRPCInternal call
bochk_relay/PythonBOCHKRequest forwarding proxyHTTPInternal forwarding
hsbc_bank_flow_service/PythonHSBCMT910 statement parsing, SFTP pull, GPG encryptionSFTP+GPGBank → moomoo (push + pull)
hsbc_edda_report/PythonHSBCeDDA report downloadSFTPmoomoo → Bank (scheduled pull)
sba_hsbc_eddi/PythonHSBCeDDA/eDDI Deposit direct debit integrationREST APImoomoo → Bank (initiate + poll)
sba_hase_eddi/PythonHang SengeDDA/eDDI Deposit direct debit integrationREST APImoomoo → Bank (initiate + poll)
scb_service/GoSCBFPS RPC interfaceSRPCmoomoo → Bank
cgb_fps_service/GoCGBFPS real-time transferSM2 encryptionmoomoo → Bank
icbc_be_relay/PythonICBCBank-enterprise relayRSA signature verificationmoomoo → Bank
cmb_stock_trans/PythonCMBBST transfer (Socket binary bidirectional link)SM2 SocketBidirectional real-time
ms_stock_bank_transaction/PythonCMBCBST transferSM2 SocketBidirectional real-time

SBA Orchestration Layer (3)

ServiceLanguageResponsibilityState Count
sba_deposit_system/PythonDeposit Orchestration: create → review → Risk Control change → credit, supports 6 Deposit modes6
sba_cash_withdraw_system/PythonWithdrawal Orchestration: freeze → deduct → transfer → release, supports 4 phases and 17 states17
sba_fund_withdraw/PythonFund Withdrawal: money market fund redemption → Withdrawal one-click Orchestration

Risk Control (3)

ServiceLanguageResponsibilityOperations Impact
hk-deposit-blacklist-go/GoDeposit blacklist (bulk add/remove/query)Hit blocks the Deposit; Procedure → manual_confirm
hk-deposit-whitelist-go/GoDeposit whitelistWhitelisted users take the fast track, skipping manual review
hk-withdraw-blacklist-go/GoWithdrawal blacklistHit sends the Withdrawal into the manual review queue

Other (9)

ServiceLanguageResponsibilityStatus
bank-card/PHPBank Card base APILegacy service, gradually migrating to bankcard_service
cash_service/PHPCash service extensionActive
refund/PHPRefund processingActive
airstar_service/GoAirstar bank payment gateway (Mandate authorization / Deposit / Withdrawal)Active — core of Airstar BST
sync_bst_data_helper/PythonCMB abnormal statement recoveryCompensation service — used when CMB Socket disconnects
tools-pic-upload/GoVoucher image uploadActive
bank_conn_doc/-Bank integration specification documents (HSBC/BOCHK/Hang Seng/ICBC/EWB/SPD)Documentation repository
procedure_system/PythonProcedure Orchestration system (SBA core framework)Active — the underlying engine of SBA

Database Architecture

Three Core Databases

DatabaseOwning ServiceCore TablesSharding StrategyEstimated Volume
Primary DB (cash_deposit / cash_withdraw)deposit/, withdraw/, cash/, refund/applys, flows, matches, tasks, queueapplys sharded by uid modulo 100; flows sharded by bank type + monthMillions/month
web_accountbankcard_service/bank_card, bank_info, bank_card_certificate, bank_card_asb_bst, bank_card_eddaNot shardedHundreds of thousands
SBA Procedure DBprocedure_system/, sba_*_system/proc_info, proc_cash_deposit, proc_cash_withdraw, flowNot shardedMillions/month

The three databases are physically isolated; services communicate via RPC calls rather than direct cross-database queries.

Impact of Sharding on Operations

Deposit application table applys is sharded into 100 tables by user ID (applys_00 through applys_99). CRM search is unaffected (uses ES), but if you need to query the database directly for troubleshooting, you must first calculate the table suffix from the user ID: uid % 100.

Bank Statement table flows is sharded by bank + month (e.g., flows_bochk_202604); cross-month queries require specifying the correct month.

Withdrawal task table tasks is not sharded, but for large data volumes, queries use indexes on created_at + status.

SBA Procedure table proc_info is not sharded; queries use id or nn_uid + biz_type.

Data Sync Pipeline (Canal CDC → Elasticsearch)

The CRM Operations console supports fuzzy search by card number, username, Bank Statement reference, etc. — this does not query the database directly but rather Elasticsearch. Data is synced in real time via Canal (Alibaba's open-source MySQL Binlog subscription tool):

PM perspective: CRM search results are near real-time (second-level latency). If a search returns "not found," it does not necessarily mean the data doesn't exist — it may be a Canal sync delay. Waiting a few seconds and searching again usually resolves it.

Canal-Synced Entities
EntitySource TableES Index PurposeSupported Search FieldsCRM Search Entry Point
ApplySyncDeposit applications applysCRM Deposit list searchuid, Bank Card number, amount, status, creation timeDeposit Management → Search
FlowSyncBank Statements flowsCRM statement search, Matching troubleshootingstatement reference, amount, bank, currency, credit timeStatement Management → Search
TaskSyncWithdrawal tasksCRM Withdrawal list searchuid, target card number, amount, status, creation timeWithdrawal Management → Search
FileSyncVoucher filesCRM voucher searchfilename, upload time, associated uidVoucher Management
DepositSbaListSyncDeposit SBA associationDeposit–Procedure association queryapply_id, procedure_idDeposit Details → SBA Association
ApplyAdditionSyncDeposit supplementary infoSupplementary search fieldsremarks, additional tagsDeposit Details → Supplementary Info

Troubleshooting steps when a record cannot be found:

  1. Wait 5–10 seconds and search again (Canal sync delay)
  2. Try different search criteria (e.g., use uid instead of card number)
  3. Check Canal Consumer logs for errors
  4. Query the database directly to confirm whether the data exists

Inter-Service Communication

ProtocolUse CaseTypical CallCharacteristicsPM Significance
SRPC (Protobuf RPC)Core services ↔ SBA / Risk Controldeposit/ calls CashDepositCreateSynchronous, strongly typed, millisecond-levelTimeout directly affects user wait time
HTTP RESTBank Card service / Airstar gateway / CRMCRM calls /bank_card/get_listStandard Web APIEasy to monitor and debug
SM2 SocketCMB/CMBC BSTBinary bidirectional linkPersistent connection, real-time pushBank-side results arrive in seconds
REST API (polling)Airstar BST / HSBC & Hang Seng eDDAAsbBstCreateResultJob pollingRequires active queryingLonger user wait time
RabbitMQTrade notification → Risk Control; cross-service asyncRmqReportMsg triggers Risk Control updateAsync decouplingQueue backlog affects batch processing

Impact of Communication Methods on Latency

ScenarioCommunication PathTypical LatencyLatency ReasonImpact Scope
BST Deposit (CMB/CMBC)SM2 Socket real-time pushSecondsBank actively pushes resultSingle
BST Deposit (Airstar)REST API + pollingSeconds to minutesPolls up to 60 timesSingle
BST Withdrawal (Airstar)REST API + pollingSeconds to minutesPolls up to 10 timesSingle
eDDA Direct Debit DepositREST API + pollingT+0 to T+1Bank processes asynchronouslySingle
Standard Deposit MatchingScheduled taskEvery 3 minutesMatching engine runs on scheduleBatch
Online Banking WithdrawalManual operationHours to daysDepends on Operations completing transfer via online bankingSingle
CRM SearchCanal CDC → ESSecondsBinlog sync delayCRM

PM perspective: If a Deposit is experiencing unusual delay, the bottleneck may be in an SRPC synchronous call (e.g., SBA Procedure creation timeout) or Canal async queue backlog. SRPC issues affect individual transactions; queue backlog affects batches.


Deposit Data Flow: How Funds Arrive

Standard Deposit (User Perspective)

StepUser ActionUser PerceptionExpected Duration
1Select Bank Card in App, get Deposit account infoSees moomoo receiving account numberInstant
2Transfer to moomoo account via banking app / online bankingBank shows transfer successful1–5 minutes
3Wait for system to match and creditApp shows "Deposit processing"3 minutes to hours
4Deposit completeApp balance increases, notification received

System Perspective

Core Tables in the Deposit Data Path

PhaseTable NameSharding RuleDescriptionOperations View Location
1. User applicationapplys_{00-99}uid % 100One row = one Deposit applicationCRM → Deposit Management
2. Bank Statementflows_{bankType}_{YYYYMM}Bank type + monthOne row = one Bank Statement entryCRM → Statement Management
3. Matchingmatches_{shard}Association record between Flow and ApplyCRM → Matching Records
4. Deposit taskdeposits_{shard}Matched Deposit tasksCRM → Deposit List
5. Anomalyabnormal_depositsNot shardedAbnormal statements tracked separatelyCRM → Abnormal Deposits
6. SBAproc_info + proc_cash_depositNot shardedProcedure tracking recordsCRM → SBA Management

Full state machine and field descriptions for Deposit Procedures → SBA Funds Orchestration - Deposit Procedure State Machine


Withdrawal Data Flow: How Funds Are Sent Out

Withdrawal (User Perspective)

StepUser ActionUser PerceptionExpected Duration
1Select Withdrawal Bank Card and amount in AppInstant
2Confirm WithdrawalAvailable balance decreases (frozen)Instant
3Wait for system processingApp shows "Withdrawal processing"BST: seconds / Online banking: hours
4Withdrawal completeReceives Withdrawal success notification
5Bank arrivalBank Card receives funds1–3 business days

System Perspective

Core Tables in the Withdrawal Data Path

PhaseTable NameDescriptionOperations View Location
1. Create tasktasksWithdrawal task core recordCRM → Withdrawal Management
2. Operation logflowsOperation log for each Approval step (staff_id, action, step)CRM → Operation Records
3. Event queuequeueAsync events (BST sync, high-risk checks, etc.)Internal system
4. SBA trackingsba_listWithdrawal Task ↔ SBA Procedure associationCRM → SBA Status
5. BST settingsauto_settingsAuto-Approval balance/limit config by bank × currencyCRM → BST Settings
6. Bank Statementcmb_list / ms_listWithdrawal records initiated from the CMB/CMBC bank sideCRM → BST Withdrawal

Full state machine for Withdrawal Procedures (17 states) and the freeze-transfer-release pattern → SBA Funds Orchestration - Withdrawal Procedure State Machine


Bank Statement Collection Frequency

Different banks have vastly different statement retrieval methods and frequencies — this directly affects Deposit crediting speed:

BankCollection MethodFrequencyNotesExpected Deposit CreditingAutomation Level
BOCHKB2E active pull3x daily (06:00/07:00/08:00) + 2-hour conversionTodayActivity → AcctStatement → AcctActivityT+0 (same day)Semi-auto
HSBCMT910 real-time push + SFTP pullReal-time + batch fallbackTransaction Reference Number deduplicationMinutesFully auto
ICBCBank-enterprise active pullDaily real-time pullQuery by date range, RSA signature verificationT+0Semi-auto
CMBBidirectional link passive receiveEvent-driven (real-time)Received in real time when bank initiatesSecondsFully auto
CMBCBidirectional link passive receiveEvent-driven (real-time)Received in real time when bank initiatesSecondsFully auto
AirstarREST API pollingPolling (up to 60 times)Polls for result after Deposit creationSeconds to minutesFully auto
Hang SengeDDA direct debit + REST APIPoll after initiating debitProcessed via sba_hase_eddiT+0 to T+1Fully auto
EWBCSV + BAI2 fileOn-demand uploadCSV deduplication + BAI2 name supplementManual processingManual
Other banksDeposit Matching task scanEvery 3 minutesCCB Asia, DBS, ZA Bank, etc.3 minutes to hoursSemi-auto

Statement retrieval delay ≠ crediting delay

Statement retrieval is only the first step of the Deposit process. Afterward, the Matching engine must compare records (every 3 minutes), SBA creates a Procedure, Risk Control changes are applied, and more. BST Channels skip the Matching step (directly creating a Procedure), which is why they credit the fastest.

Cumulative latency estimates by stage:

Deposit ChannelStatement RetrievalMatchingSBA + Risk ControlTotal
BST (CMB/CMBC)SecondsSkippedMillisecondsSeconds
BST (Airstar)Seconds to 3 minSkippedMillisecondsSeconds to 3 min
eDDA (Hang Seng/HSBC)T+0 to T+1SkippedMillisecondsT+0 to T+1
Standard Deposit (HSBC)Minutes3 minMilliseconds3–10 minutes
Standard Deposit (BOCHK)3x daily3 minMillisecondsHours
Standard Deposit (Other)3 min3 minMilliseconds6–30 minutes

Request Tracing

Deposit Trace Example: A CMB BST Deposit

User initiates BST Deposit of 10,000 HKD via CMB banking app

① cmb_stock_trans receives SM2 Socket push (< 1 sec)
    → Decrypts message, extracts: card number, amount, currency, market

② deposit/ receives Deposit notification (SRPC, < 100ms)
    → Creates Apply record (applys_xx table)
    → Blacklist/whitelist check (parallel RPC)

③ sba_deposit_system/ creates Procedure (SRPC, < 100ms)
    → Writes proc_info + proc_cash_deposit
    → Auto-review (deposit_type = TRANS_AUTO)

④ Risk Control system asset change (SRPC, < 200ms)
    → Balance increases by 10,000 HKD

⑤ Procedure → end_ok(deposit_ok) (< 50ms)
    → Writes back Apply status → DONE
    → Canal syncs to ES (< 3 sec)

⑥ User sees balance increase in App
    Total elapsed: ~1–3 seconds

Withdrawal Trace Example: An Online Banking Withdrawal

User initiates 50,000 HKD Withdrawal to Hang Seng Bank via moomoo App

① withdraw/ creates Task (< 100ms)
    → Blacklist check
    → Bank Card verification (bankcard_service/ HTTP)
    → Step 1 Audit: auto-pass (standard template)
    → Step 2 Confirm: parameter validation
    → Step 3 Remittance: create SBA Procedure

② sba_cash_withdraw_system/ freezes funds (< 200ms)
    → Risk Control system freezes 50,000 HKD
    → Procedure: new(freeze) → new(waiting) → new(blank)

③ Deduction (< 200ms)
    → Risk Control system formally deducts 50,000 HKD
    → Procedure: pending(deduct_done)

④ Enter manual transfer (Hang Seng uses corporate online banking)
    → Procedure: pending(transfer_manual)
    → **Awaiting Operations to complete transfer via Hang Seng corporate online banking**

⑤ After Operations completes transfer on online banking (hours to days)
    → Click "Confirm Transfer Complete" in CRM
    → SetManualTransferDone
    → Procedure: end_ok(transfer_done)

⑥ User receives funds 1–3 business days later
    Total elapsed: hours to 1 business day (depends on Operations processing speed)

Monitoring & Alerting

Core Monitoring Metrics

MetricMonitoring MethodAlert ThresholdImpact
Deposit crediting timeTime from SBA Procedure creation to end_okBST > 5 min / Standard > 1 hourUser experience
Withdrawal processing timeTime from Task creation to end_okBST > 10 min / Online banking > 24 hoursUser experience
Matching engine executionScheduled task execution logsNot executed for > 6 minutesBatch Deposit delays
Canal sync delayES latest record time vs MySQL latest record timeDelay > 30 secondsCRM cannot find latest data
SM2 Socket connectionHeartbeat detection (CMB/CMBC)Heartbeat timeout > 60 secondsBST Channel unavailable
Polling task timeoutJob retry_countDeposit > 60 / Withdrawal > 10Airstar BST transaction stuck
Freeze not releasedProcedure duration in pending(unfreeze)> 5 minutesUser funds stuck
Reversal failureProcedure duration in pending(return)> 5 minutesUser funds "disappear"

Alert Notification Methods

SeverityAlert MethodResponse SLATypical Scenario
P0 CriticalFeishu group + phone callWithin 15 minutesFreeze not released, reversal failure, SM2 Socket disconnection
P1 ImportantFeishu groupWithin 30 minutesPolling timeout, Matching engine stopped, prolonged Canal sync delay
P2 NormalFeishu groupWithin 2 hoursIndividual Deposit/Withdrawal delay exceeds expectations

Detailed alert rule configuration, scheduled task inventory, and Dashboard URLs → Scheduled Tasks & Monitoring


Common Latency Bottlenecks & Troubleshooting

When Deposits or Withdrawals experience delays, the issue typically lies in one of the following areas:

#BottleneckSymptomTroubleshooting ApproachImpact ScopeSeverity
1Bank Statement not receivedApply created but no Matching statementCheck the corresponding bank integration service logs; confirm whether the bank side has completed the transferSingleP2
2Matching engine delayStatement in database but not matched to ApplyCheck whether the Matching scheduled task is running normally (every 3 minutes)BatchP1
3SBA Procedure creation timeoutMatch successful but Procedure not createdCheck whether SBA service is healthy, whether SRPC is timing outSingleP1
4Risk Control change failedProcedure created successfully but status is end_rejectCheck the Procedure's reason fieldSingleP2
5Canal sync delayCRM cannot find existing recordsWait a few seconds and search again; check whether Canal Consumer is running normallyCRMP2
6BST polling timeoutAirstar BST Deposit/Withdrawal stuck in processingCheck polling task retry count (Deposit 60 / Withdrawal 10)SingleP1
7Scheduled script not runningWithdrawal Procedure stuck at new(waiting)Check whether the Withdrawal scheduled script is executing normallyBatchP0
8Manual transfer not confirmedWithdrawal Procedure stuck at pending(transfer_manual)Remind Operations to confirm after completing the transfer via online bankingSingleP2
9SM2 Socket disconnectionCMB/CMBC BST Channel completely unavailableCheck cmb_stock_trans / ms_stock_bank_transaction service statusChannel-wideP0
10RabbitMQ backlogMultiple Deposits/Withdrawals delayed in batchCheck queue depth and consumer statusBatchP1

Quick Troubleshooting Decision Tree


Inter-System Call Relationships

After Reading

I want to...Go to
Understand what the system covers and what it doesn'tGetting Started - 30-Second Overview
Dive deeper into SBA OrchestrationSBA Funds Orchestration
Dive deeper into the Bank Card systemBank Cards & Authorization
See integration methods for each bankBank Capability Matrix
See alerts and scheduled tasksScheduled Tasks & Monitoring
Was this page helpful?

内部业务文档 · 仅限 moomoo 团队使用