mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-03 21:18:19 +07:00
[GH-ISSUE #6252] [Feature]:Scale Client CRUD by Client–Inbound Edge Count and Batch Multi-Node Synchronization per Node #4245
Labels
No labels
backlog
bug
clarification needed
documentation
duplicate
enhancement
github_actions
good first issue
invalid
javascript
New Feature
PR welcomed
pull-request
question
wontfix
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
MHSanaei/3x-ui#4245
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Originally created by @HamedSanaei on GitHub (Aug 18, 2026).
Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/6252
Is your feature request related to a problem?
3x-ui has received significant client scalability improvements in recent releases, including bulk SyncInbound, scalable add/delete operations, SQL-backed client pagination, and reusing one email/subId snapshot during client fan-out.
However, client CRUD latency still grows significantly with the number of inbounds attached to a client, especially when those inbounds belong to remote nodes.
This enhancement proposes optimizing scalability by client–inbound edge count and node fan-out, rather than only by the total number of clients.
Describe the solution you'd like
A production topology where this becomes visible:
5,000+ unique clients
Each client attached to approximately 8 inbounds
Approximately 40,000+ client–inbound relationships
One master panel
Two or more connected nodes
PostgreSQL backend
Observed operations:
Create client: 60–120 seconds
Attach client to inbounds: 60–120 seconds
Update client: significant delay
Client-related API calls: significant delay
Inbounds and client pages become increasingly expensive as the topology grows
The latency correlates much more strongly with the number of attached inbounds and remote-node fan-out than with the raw number of unique clients.
Alternatives you've considered
Bulk SyncInbound
Removal of quadratic client operations
Chunked IN queries
SQL-backed clients page pagination/filtering
One email/subId snapshot per client fan-out instead of one snapshot per inbound
These changes significantly improved large-client scenarios.
The remaining problem appears to be a different scaling dimension: membership edges and remote node fan-out.
Create/Attach iterates over target inbound IDs and applies the client to each inbound individually.
For remote inbounds, a client operation can result in a synchronous remote-node operation for each inbound.
The previous performance work already identified the remaining dominant cost as a synchronous, 10-second-capped node round-trip per remote inbound, which can multiply again with chained nodes.
This means a topology with 8 remote inbounds can potentially spend roughly:
8 inbounds × up to 10 seconds
≈ 80 seconds
in node synchronization alone.
Proposed Enhancement
Collect all affected inbounds first, group them by node, and synchronize once per distinct node.
Instead of:
Inbound A -> Node 1
Inbound B -> Node 1
Inbound C -> Node 1
Inbound D -> Node 2
Inbound E -> Node 2
use:
Node 1 -> batch [A, B, C]
Node 2 -> batch [D, E]
An even more scalable design would be:
Commit DB transaction
↓
Mark affected node/generation dirty
↓
Return API response
↓
Coalesced node reconciliation
If asynchronous reconciliation is not desirable, bounded parallel synchronization per distinct node would still avoid sequential per-inbound latency.
SyncInbound currently removes all client_inbounds relationships for an inbound and recreates the complete relationship set.
For an inbound containing 5,000 clients, attaching or modifying one client can therefore cause thousands of unrelated membership rows to be deleted and inserted again.
With one client being attached to 8 large inbounds, this may result in tens of thousands of relationship mutations for a logically very small change.
This creates unnecessary:
PostgreSQL writes
index updates
WAL generation
dead tuples
autovacuum pressure
transaction work
Proposed Enhancement
Normal CRUD should perform delta operations.
For attach:
INSERT INTO client_inbounds (client_id, inbound_id)
VALUES (?, ?)
ON CONFLICT DO NOTHING;
For detach:
DELETE FROM client_inbounds
WHERE client_id = ?
AND inbound_id = ?;
Full SyncInbound should remain available for:
migration
import
explicit reconciliation
integrity repair
For bulk changes, compute a set difference and insert/delete only changed membership edges.
The database already contains normalized client records, with indexed email/subId fields.
However, identity collection still expands settings.clients JSON across inbounds.
In a topology with:
5,000 clients × 8 memberships
≈ 40,000 embedded client entries
a logically simple uniqueness lookup can require scanning a much larger JSON-derived relation.
Proposed Enhancement
Use indexed normalized lookups from clients for email/subId validation.
For example:
SELECT id
FROM clients
WHERE email = ?
OR sub_id = ?
LIMIT 1;
The normalized tables should be the source of truth for:
client identity
client/inbound relationships
uniqueness checks
membership queries
client counts
list pagination
inbounds.settings.clients can remain a generated/config representation if required for Xray compatibility, but it should not be required for global metadata queries.
Adding a client currently requires loading the complete inbound settings JSON, decoding the complete client array, changing it, encoding the entire settings document, and saving the inbound again.
The cost therefore grows with the number of clients already attached to the inbound even when only one client changes.
Long term, reducing the role of settings.clients as a primary data representation would significantly improve scalability.
The slim inbounds endpoint reduces the returned client data, but the backend can still fetch and parse full inbound settings before slimming the response.
For panels with many large inbounds, the list page should use a metadata-only query.
For example, the list operation should retrieve only fields required by the UI:
id
remark
protocol
port
enable
traffic
expiry
status
Client counts or badges can be obtained with an aggregate query over client_inbounds.
The full settings JSON should only be fetched when opening/editing one specific inbound.
Concrete use case
Current large-scale tests should be complemented with a topology benchmark based on relationship count and node fan-out.
Suggested PostgreSQL scenario:
5,000 unique clients
8 inbounds per client
≈40,000 client-inbound relationships
2 remote nodes
Measure:
Create one client attached to 8 inbounds
Attach existing client to 8 inbounds
Update one client
Detach one client
Paginated clients API
Inbounds list API
Capture:
wall-clock latency
SQL query count
rows inserted/deleted
PostgreSQL WAL/write activity
node RPC count
p50/p95 request latency
Also compare:
1 local inbound
1 remote inbound
4 remote inbounds
8 remote inbounds
This would expose scaling by node fan-out separately from scaling by raw client count.
Suggested Acceptance Criteria
A successful implementation should ensure that:
Updating or attaching one client does not delete and recreate unrelated client_inbounds rows.
Client email/subId uniqueness checks do not require a global expansion of all inbound client JSON.
Node synchronization complexity is proportional to the number of affected nodes rather than the number of remote inbounds.
Multiple changed inbounds belonging to the same node can be propagated in one synchronization operation.
Inbounds list APIs do not need to fetch and parse complete settings.clients payloads.
Performance tests cover client–inbound edge count and remote-node fan-out in addition to raw client count.
Why This Is an Enhancement Rather Than a Regression Report
Recent releases already contain substantial scalability improvements for large client databases.
This proposal targets the next scaling dimension: environments where a moderate number of unique clients creates a much larger number of client–inbound relationships and remote-node synchronization operations.
The goal is to make client CRUD complexity closer to the size of the actual change rather than the total size of every affected inbound.
Mockups, screenshots, or examples
Which parts of the panel would this affect?
No response
Are you willing to help?
Before submitting
@github-actions[bot] commented on GitHub (Aug 18, 2026):
All five items in this proposal check out against the source at
380aff4. Details per point, with the caveats where the current code is already partly where you want it.1. Node synchronization is per-inbound, not per-node — confirmed.
ClientService.Createiteratespayload.InboundIdsand callsaddInboundClientonce per inbound (internal/web/service/client_crud.go:202-224);Attachhas the same shape (client_crud.go:740-766). Each call independently resolves its own target vianodePushPlan(internal/web/service/client_inbound_apply.go:427) and issues its ownrt.AddClient(client_inbound_apply.go:509-519). There is no grouping by node and no parallelism — I grepped forerrgroup/sync.WaitGroup/goroutines acrossclient_crud.go,client_inbound_apply.goandclient_bulk.goand there are none. The per-request cap isremoteHTTPTimeout = 10 * time.Second(internal/web/runtime/remote.go:29), and one remote inbound in this path costs one HTTP round-trip (AdvancePushedInboundatremote.go:533is local bookkeeping only). Your 8 × 10 s arithmetic therefore matches the code.Worth noting: the coalesced-reconciliation half of your diagram already exists.
addInboundClientcallsMarkNodeDirtyTxinside the commit (client_inbound_apply.go:453-455,service/node.go:1010), andnode_traffic_sync_jobpicks upConfigDirtyand runsReconcileNodeon a@every 5sschedule (internal/web/job/node_traffic_sync_job.go:366-376). The synchronous push runs in addition to it, not instead of it. There is also already a bulk escape hatch atnodeBulkPushThreshold = 32(internal/web/service/inbound_node.go:28), but it keys on client count within one inbound, so a 1-client × 8-inbound fan-out never trips it.2. Full
client_inboundsreconciliation on ordinary CRUD — confirmed.SyncInbounddeletes every membership row for the inbound (internal/web/service/client_link.go:86) and re-inserts the complete set (client_link.go:190-194).addInboundClientcalls it withGetClients(oldInbound), i.e. the inbound's entire post-save client list, not the delta (client_inbound_apply.go:446-452).One amplifier you did not list: that transaction runs through
runSerializedTx(client_inbound_apply.go:434), which funnels into a single global traffic-writer queue (internal/web/service/traffic_writer.go:126-151). So the delete/re-insert churn does not only cost WAL and dead tuples — it occupies the one serialized writer shared with traffic accounting, which is likely why concurrent client API calls degrade together rather than independently.3. Identity lookups — partly normalized already.
Createalready does indexed lookups against the normalized table for both checks: email atclient_crud.go:159and subId atclient_crud.go:186-188, andClientRecord.EmailisuniqueIndexwithSubIDindexed (internal/database/model/model.go:908-909). What remains on the JSON path isgetAllEmailSubIDs(internal/web/service/inbound.go:479-510), which expandsjsonb_array_elements(inbounds.settings::jsonb -> 'clients')across every inbound (internal/database/dialect.go:18-23) and feedscheckEmailsExistForClients(client_inbound_apply.go:242-270). That is the ~40k-row unindexed scan in your topology, and it runs once perCreate/Attach.A straight swap to
clientswould change semantics, though:getAllEmailSubIDsdeliberately maps an email seen with two different non-empty subIds to""so neither identity can claim it (inbound.go:477-478,501-505). A unique-emailclientstable cannot represent that conflict state, so replacing the scan needs a decision about how desynced legacy rows are handled.4. Whole-settings rewrite per mutation — confirmed.
addInboundClientunmarshals the full settings, appends, and re-serializes withjson.MarshalIndentbeforetx.Save(client_inbound_apply.go:401-423,443). The pretty-printing makes the re-encode and the stored column meaningfully larger than compactMarshalwould.5. Inbounds list still reads and parses full settings — confirmed.
GetInboundsSlimruns an unprojectedFind(&inbounds)(internal/web/service/inbound.go:209) and then parses each inbound's settings to strip client fields (inbound.go:223,slimSettingsClientsatinbound.go:231). Slimming reduces the response payload; the DB read and the JSON parse of every client array still happen server-side, exactly as you describe.One thing I need before this can be sized correctly. The feature form does not collect a version, and your measured numbers (60–120 s, and "up to 10 minutes" in the attachment) are the same order as #6035 and #6091 — both closed as completed on 2026-07-23/24, ahead of
v3.6.0(released 2026-07-30). Whether this is genuinely the next scaling dimension or partly the already-addressed one depends on which build produced those numbers:x-uion the server).NodeID != nil) versus local, and whether any of those nodes are themselves masters with further children — the per-inbound round-trip compounds across hops.EXPLAIN (ANALYZE, BUFFERS)on thejsonb_array_elementsquery from point 3, pluspg_stat_statementstop rows during a create, would separate the two cleanly.I could not read the attached image, so please paste the request timing and any error text as text rather than a screenshot.
Related but distinct, not duplicates: #6035 and #6091 (raw client count, closed) and #6065 (subId uniqueness across multi-node clients, open) — the last one touches the same
getAllEmailSubIDssemantics discussed in point 3.@MHSanaei for a decision on scope and priority; points 2 and 5 look like the smallest changes with the largest effect, and neither requires the async reconciliation redesign.
This reply was generated automatically. A maintainer may follow up.
@HamedSanaei commented on GitHub (Aug 18, 2026):
Thanks for the detailed verification.
To clarify: this issue is reproducible on 3x-ui v3.6.0, so the measurements are not from a version prior to the fixes in #6035 / #6091.
I upgraded to v3.6.0 and the scalability problem is still present in production.
My current topology is:
3x-ui v3.6.0
PostgreSQL backend
5,000+ unique clients
approximately 8 inbounds per client
approximately 40,000+ client–inbound relationships
1 master panel
3 connected remote nodes
8 total target inbounds:
The problem becomes significantly worse as the number of inbounds attached to each client increases.
In particular, client creation through the API can still take 60–120 seconds, and in some cases I have observed requests taking several minutes / up to approximately 10 minutes.
So unfortunately the performance improvements from #6035 and #6091 did not resolve this production case.
The important point is that the bottleneck appears to scale with client–inbound relationships and node fan-out, rather than only with the number of unique clients.
Your source analysis also seems to confirm the two paths I am most concerned about:
A single client operation still performs synchronous work per remote inbound, instead of grouping changes per node.
Ordinary client CRUD still calls SyncInbound, causing the complete client_inbounds relationship set of an affected inbound to be deleted and recreated.
The second point is particularly important in my environment because each affected inbound can contain thousands of clients.
Regarding the exact remote/local split of the 8 target inbounds, I will verify the exact distribution from the production database, but multiple target inbounds are on the connected remote nodes and the slowdown becomes progressively worse as those remote inbounds are included.
I can also provide EXPLAIN (ANALYZE, BUFFERS) and pg_stat_statements results if useful, but I want to emphasize that the original performance problem is still reproducible on v3.6.0.
Therefore I don't believe this is the already-fixed raw-client-count problem from #6035/#6091. This appears to be the remaining edge-count / multi-node fan-out scalability problem described in this issue.
I am happy to run additional benchmarks or test a PR against the production-scale topology.
@github-actions[bot] commented on GitHub (Aug 18, 2026):
Thank you — the version and the inbound split are exactly what was missing, and together they change the diagnosis: with 5 local and 3 remote inbounds, one per node, per-node batching (your item 1) cannot be the dominant term. Grouping 3 inbounds that sit on 3 distinct nodes produces 3 groups, so batching saves nothing in this specific topology, and the whole node fan-out is bounded by 3 x
remoteHTTPTimeout= 30 s (internal/web/runtime/remote.go:29, applied atremote.go:226). That does not reach 60–120 s, and it is nowhere near 10 minutes. Your item 2 does scale the way you describe, and there is a third factor that is not in your list and that best explains the multi-minute outliers.Item 2 is the dominant local term, and it is O(total edges) per create.
ClientService.Createloops overpayload.InboundIdsand callsaddInboundClientonce per inbound (internal/web/service/client_crud.go:202-224). Each iteration, for an inbound holding N clients:compactOrphansrunsceil(N/400)chunkedSELECT ... WHERE email IN (...)(client_inbound_apply.go:412,client_locks.go:41-91);json.MarshalIndentand the wholesettingsblob is written back viatx.Save(client_inbound_apply.go:417,443);SyncInbounddeletes every membership row for that inbound (client_link.go:86), re-reads the client records in chunks of 400 (client_link.go:106-116), and re-inserts the complete edge set withCreateInBatches(links, 200)(client_link.go:190-194). It is called withGetClients(oldInbound), i.e. the inbound's entire post-save client list, not the delta (client_inbound_apply.go:446-452).At 40,000 edges over 8 inbounds, N is roughly 5,000 per inbound, so one single-client create costs on the order of 40,000
client_inboundsrow deletions plus 40,000 re-insertions (about 200 multi-rowINSERTstatements), around 200 chunkedSELECTs, and 8 full read/parse/pretty-print/write cycles over ~5,000-element client arrays. That is proportional to the total edge count, which matches your observation that the problem worsens with inbounds-per-client rather than with unique clients.The third factor: a single client create is serialized twice, and that is what produces the 10-minute tail. This is the part neither of your two items covers, and it is confirmed in the source:
addInboundClienttakes a per-inbound mutex for its entire duration, including the post-commit node push:defer lockInbound(data.Id).Unlock()(client_inbound_apply.go:281, lock atclient_locks.go:29-39). Every one of your clients is attached to the same 8 inbounds, so concurrent create calls contend on those same 8 mutexes. k concurrent creates cost roughly k x the single-create time, which is how a 60–120 s operation becomes several minutes without anything else changing.runSerializedTxsubmits to the single traffic-writer queue (internal/web/service/traffic_writer.go:126-130, one consumer started attraffic_writer.go:41-63), which is shared with the@every 5straffic poll (AddTraffic->submitTrafficWrite,internal/web/service/inbound_traffic.go:28-34; cadences atinternal/web/web.go:292and:296). So the ~10,000 row mutations per inbound queue behind, and ahead of, traffic accounting.One string is worth grepping for on the master, since it separates these paths without any instrumentation:
That warning is emitted whenever a remote push fails or times out (
client_inbound_apply.go:512); the default log folder is/var/log/x-uiand the panel file is3xui.log(internal/config/config.go:245,internal/logger/logger.go:22). Separately, if the serialized writer ever backs up past its 5 s submit timeout with the 256-deep queue full, the create fails with the error texttraffic writer queue fullin the API response rather than merely running slowly (traffic_writer.go:16-19,:168).Why the 3 remote inbounds still cost more than a network hop.
Remote.AddClientresolves the tag (a cache miss adds a second round trip viarefreshRemoteIDs,remote.go:299-310) and then POSTspanel/api/clients/addon the node (remote.go:557-570). That is the same route and the same handler the master exposes (internal/web/controller/api.go:97->internal/web/controller/client.go:182->ClientService.Create), so the master's 10 s budget has to cover the node executing the full create path, including the node's ownSyncInboundover its own inbound. If the node-side inbound also holds thousands of clients, that will exceed 10 s routinely; the master then logs the warning above, setspush = false, and falls back to the dirty flag plusReconcileNodeon the@every 5snode sync job (client_inbound_apply.go:506-519;internal/web/job/node_traffic_sync_job.go:366-381,nodeReconcileTimeout30 s at:21).advancePushedInboundis in-memory bookkeeping only and costs nothing (remote.go:533-541). Note also that the existing bulk escape hatch,nodeBulkPushThreshold = 32(internal/web/service/inbound_node.go:24-28), keys on client count within one inbound, so a 1-client x 8-inbound fan-out never trips it. This is inference about your node timings, not something I can confirm from here — the grep above settles it.Your test-coverage acceptance criterion is accurate. Every existing Postgres scale test drives a single inbound:
TestAddDelClientPostgresScaleseeds one inbound and issues oneAddInboundClientagainst it (internal/web/service/sync_scale_postgres_test.go:162-217), and no scale test exercises a remote node. So edge count and node fan-out have no regression guard today, exactly as you state.On the data you offered.
EXPLAIN (ANALYZE, BUFFERS)on the identity query is useful but likely secondary:getAllEmailSubIDsnow runs once per create, not once per inbound (client_crud.go:196), so itsjsonb_array_elementsexpansion over ~40,000 entries is paid once. On Postgres the statement is:(assembled at
internal/web/service/inbound.go:485-490frominternal/database/dialect.go:18-23). What would be decisive instead ispg_stat_statementsfor one create, filtered toclient_inbounds— specifically thecalls,rowsandtotal_exec_timeof theDELETE FROM "client_inbounds" WHERE inbound_id = $1and the corresponding multi-rowINSERT. If those two account for the bulk of the wall clock, item 2 is confirmed as the primary cost and item 1 is secondary in your topology; if they do not, the remaining time is in the node round trips and the lock contention above.@MHSanaei this is now a concrete, source-confirmed scaling problem rather than a general request. The three separable pieces, in descending expected effect for this reporter's topology: delta membership writes instead of full
SyncInboundon ordinary CRUD (removes the O(total edges) term), narrowing thelockInboundhold so it does not span the node push and the full rewrite, and per-node grouping of remote pushes (little effect at 1 remote inbound per node, but correct for the general fan-out case).Confidence: High for everything attributed to a file and line above; the attribution of the specific 60–120 s and 10-minute figures to these paths is inference until the grep or the
pg_stat_statementsrows come back.This reply was generated automatically. A maintainer may follow up.
@HamedSanaei commented on GitHub (Aug 18, 2026):
I collected pg_stat_statements data from the production PostgreSQL backend.
The current database has approximately 56k client/inbound edges, with the large inbounds holding roughly 5.9k–6k clients each.
Over a 415-second production interval, the following deltas were observed:
DELETE FROM client_inbounds WHERE inbound_id = $1
47 executions
278,801 rows deleted
INSERT INTO client_inbounds ...
1,411 INSERT statements
278,843 rows inserted
This works out to approximately:
5,932 membership rows deleted per reconciliation
5,933 membership rows recreated per reconciliation
The near 1:1 ratio between deleted and reinserted rows strongly confirms that ordinary activity is repeatedly rebuilding almost the entire membership set of large inbounds rather than applying a small delta.
The JSON identity path is also significantly more expensive than expected.
During the same 415-second interval, the query based on:
jsonb_array_elements(inbounds.settings::jsonb -> 'clients')
executed 340 times and processed:
19,083,622 rows
which is approximately:
56,128 rows per execution
Its cumulative PostgreSQL execution time increased by:
1,954,985 ms
or approximately:
5.75 seconds of execution time per call on average.
The cumulative time is larger than wall-clock because multiple requests are executing concurrently, but that is itself relevant to the production latency: this expensive global JSON expansion is being executed concurrently under load.
So the production measurements appear to confirm two independent scaling problems:
Ordinary client mutations repeatedly perform full client_inbounds reconciliation, rewriting ~5.9k membership rows for an inbound when logically only a small number of edges changed.
The JSON-based email/subId identity scan expands approximately the entire ~56k embedded-client relationship set per execution and currently averages several seconds per call under production load.
This also explains why latency rises sharply under concurrency: the expensive full-edge reconciliation and global JSON scans are repeated across overlapping requests.
I would therefore strongly prioritize:
delta client_inbounds writes for ordinary CRUD;
replacing the global JSON identity scan with normalized indexed lookups where semantics permit;
and then narrowing the serialized/locked sections so these expensive operations do not amplify each other under concurrency.
I can provide another controlled before/after measurement around a single isolated Create if needed, but the production counters already show the full-reconciliation and global-scan behavior very clearly.
@HamedSanaei commented on GitHub (Aug 18, 2026):
Hi, just following up on #6252.
This issue is still unresolved and the performance impact is quite significant in real-world large deployments. The main bottleneck is still the per-inbound remote-node synchronization and the unnecessary full reconciliation of client_inbounds.
Could you please revisit this issue and consider implementing the proposed node-level batching / delta-based synchronization?
This would make a major difference for deployments with thousands of clients and multiple remote nodes.
Thanks!