[GH-ISSUE #6252] [Feature]:Scale Client CRUD by Client–Inbound Edge Count and Batch Multi-Node Synchronization per Node #4245

Closed
opened 2026-10-31 20:38:15 +07:00 by bsakaguchi · 5 comments
Owner

Originally created by @HamedSanaei on GitHub (Aug 18, 2026).
Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/6252

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.

  1. Remote Node Synchronization Is Still Per-Inbound

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.

  1. Normal Client CRUD Still Causes Full client_inbounds Reconciliation

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.

  1. Client Identity Lookups Should Use the Normalized clients Table

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.

  1. A Single Client Mutation Rewrites the Entire Inbound Settings JSON

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.

  1. Inbounds List Should Not Require Loading Full Client Settings

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

Image it takes up to 10 minutes for creating a client using api!

Which parts of the panel would this affect?

No response

Are you willing to help?

  • I'd like to implement this feature myself and open a PR.
  • I can help test once a PR is open.

Before submitting

  • I searched existing issues and this feature has not been requested.
  • This feature request is written in English.
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. 1. Remote Node Synchronization Is Still Per-Inbound 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. 2. Normal Client CRUD Still Causes Full client_inbounds Reconciliation 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. 3. Client Identity Lookups Should Use the Normalized clients Table 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. 4. A Single Client Mutation Rewrites the Entire Inbound Settings JSON 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. 5. Inbounds List Should Not Require Loading Full Client Settings 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 <img width="639" height="907" alt="Image" src="https://github.com/user-attachments/assets/67ef4f76-04dc-4c14-967e-55a7bc109421" /> it takes up to 10 minutes for creating a client using api! ### Which parts of the panel would this affect? _No response_ ### Are you willing to help? - [ ] I'd like to implement this feature myself and open a PR. - [ ] I can help test once a PR is open. ### Before submitting - [x] I searched [existing issues](../issues?q=is%3Aissue) and this feature has not been requested. - [x] This feature request is written in English.
bsakaguchi 2026-10-31 20:38:15 +07:00
Author
Owner

@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.Create iterates payload.InboundIds and calls addInboundClient once per inbound (internal/web/service/client_crud.go:202-224); Attach has the same shape (client_crud.go:740-766). Each call independently resolves its own target via nodePushPlan (internal/web/service/client_inbound_apply.go:427) and issues its own rt.AddClient (client_inbound_apply.go:509-519). There is no grouping by node and no parallelism — I grepped for errgroup/sync.WaitGroup/goroutines across client_crud.go, client_inbound_apply.go and client_bulk.go and there are none. The per-request cap is remoteHTTPTimeout = 10 * time.Second (internal/web/runtime/remote.go:29), and one remote inbound in this path costs one HTTP round-trip (AdvancePushedInbound at remote.go:533 is local bookkeeping only). Your 8 × 10 s arithmetic therefore matches the code.

Worth noting: the coalesced-reconciliation half of your diagram already exists. addInboundClient calls MarkNodeDirtyTx inside the commit (client_inbound_apply.go:453-455, service/node.go:1010), and node_traffic_sync_job picks up ConfigDirty and runs ReconcileNode on a @every 5s schedule (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 at nodeBulkPushThreshold = 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_inbounds reconciliation on ordinary CRUD — confirmed.
SyncInbound deletes every membership row for the inbound (internal/web/service/client_link.go:86) and re-inserts the complete set (client_link.go:190-194). addInboundClient calls it with GetClients(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.
Create already does indexed lookups against the normalized table for both checks: email at client_crud.go:159 and subId at client_crud.go:186-188, and ClientRecord.Email is uniqueIndex with SubID indexed (internal/database/model/model.go:908-909). What remains on the JSON path is getAllEmailSubIDs (internal/web/service/inbound.go:479-510), which expands jsonb_array_elements(inbounds.settings::jsonb -> 'clients') across every inbound (internal/database/dialect.go:18-23) and feeds checkEmailsExistForClients (client_inbound_apply.go:242-270). That is the ~40k-row unindexed scan in your topology, and it runs once per Create/Attach.

A straight swap to clients would change semantics, though: getAllEmailSubIDs deliberately 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-email clients table 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.
addInboundClient unmarshals the full settings, appends, and re-serializes with json.MarshalIndent before tx.Save (client_inbound_apply.go:401-423, 443). The pretty-printing makes the re-encode and the stored column meaningfully larger than compact Marshal would.

5. Inbounds list still reads and parses full settings — confirmed.
GetInboundsSlim runs an unprojected Find(&inbounds) (internal/web/service/inbound.go:209) and then parses each inbound's settings to strip client fields (inbound.go:223, slimSettingsClients at inbound.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:

  1. The 3x-ui version the measurements were taken on (panel sidebar, or x-ui on the server).
  2. For the create-client call: how many of the 8 target inbounds are remote (NodeID != nil) versus local, and whether any of those nodes are themselves masters with further children — the per-inbound round-trip compounds across hops.
  3. Whether the slow calls are wall-clock-bound on node RPCs or on PostgreSQL. EXPLAIN (ANALYZE, BUFFERS) on the jsonb_array_elements query from point 3, plus pg_stat_statements top 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 getAllEmailSubIDs semantics 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.

<!-- gh-comment-id:5329487000 --> @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.Create` iterates `payload.InboundIds` and calls `addInboundClient` once per inbound (`internal/web/service/client_crud.go:202-224`); `Attach` has the same shape (`client_crud.go:740-766`). Each call independently resolves its own target via `nodePushPlan` (`internal/web/service/client_inbound_apply.go:427`) and issues its own `rt.AddClient` (`client_inbound_apply.go:509-519`). There is no grouping by node and no parallelism — I grepped for `errgroup`/`sync.WaitGroup`/goroutines across `client_crud.go`, `client_inbound_apply.go` and `client_bulk.go` and there are none. The per-request cap is `remoteHTTPTimeout = 10 * time.Second` (`internal/web/runtime/remote.go:29`), and one remote inbound in this path costs one HTTP round-trip (`AdvancePushedInbound` at `remote.go:533` is local bookkeeping only). Your 8 × 10 s arithmetic therefore matches the code. Worth noting: the coalesced-reconciliation half of your diagram already exists. `addInboundClient` calls `MarkNodeDirtyTx` inside the commit (`client_inbound_apply.go:453-455`, `service/node.go:1010`), and `node_traffic_sync_job` picks up `ConfigDirty` and runs `ReconcileNode` on a `@every 5s` schedule (`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 at `nodeBulkPushThreshold = 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_inbounds` reconciliation on ordinary CRUD — confirmed.** `SyncInbound` deletes every membership row for the inbound (`internal/web/service/client_link.go:86`) and re-inserts the complete set (`client_link.go:190-194`). `addInboundClient` calls it with `GetClients(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.** `Create` already does indexed lookups against the normalized table for both checks: email at `client_crud.go:159` and subId at `client_crud.go:186-188`, and `ClientRecord.Email` is `uniqueIndex` with `SubID` indexed (`internal/database/model/model.go:908-909`). What remains on the JSON path is `getAllEmailSubIDs` (`internal/web/service/inbound.go:479-510`), which expands `jsonb_array_elements(inbounds.settings::jsonb -> 'clients')` across every inbound (`internal/database/dialect.go:18-23`) and feeds `checkEmailsExistForClients` (`client_inbound_apply.go:242-270`). That is the ~40k-row unindexed scan in your topology, and it runs once per `Create`/`Attach`. A straight swap to `clients` would change semantics, though: `getAllEmailSubIDs` deliberately 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-email `clients` table 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.** `addInboundClient` unmarshals the full settings, appends, and re-serializes with `json.MarshalIndent` before `tx.Save` (`client_inbound_apply.go:401-423`, `443`). The pretty-printing makes the re-encode and the stored column meaningfully larger than compact `Marshal` would. **5. Inbounds list still reads and parses full settings — confirmed.** `GetInboundsSlim` runs an unprojected `Find(&inbounds)` (`internal/web/service/inbound.go:209`) and then parses each inbound's settings to strip client fields (`inbound.go:223`, `slimSettingsClients` at `inbound.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: 1. The 3x-ui version the measurements were taken on (panel sidebar, or `x-ui` on the server). 2. For the create-client call: how many of the 8 target inbounds are remote (`NodeID != nil`) versus local, and whether any of those nodes are themselves masters with further children — the per-inbound round-trip compounds across hops. 3. Whether the slow calls are wall-clock-bound on node RPCs or on PostgreSQL. `EXPLAIN (ANALYZE, BUFFERS)` on the `jsonb_array_elements` query from point 3, plus `pg_stat_statements` top 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 `getAllEmailSubIDs` semantics 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.*
Author
Owner

@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:

  • 5 local
  • 1 on Node 1
  • 1 on Node 2
  • 1 on Node 3

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.

<!-- gh-comment-id:5329549361 --> @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: - 5 local - 1 on Node 1 - 1 on Node 2 - 1 on Node 3 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.
Author
Owner

@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 at remote.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.Create loops over payload.InboundIds and calls addInboundClient once per inbound (internal/web/service/client_crud.go:202-224). Each iteration, for an inbound holding N clients:

  • compactOrphans runs ceil(N/400) chunked SELECT ... WHERE email IN (...) (client_inbound_apply.go:412, client_locks.go:41-91);
  • the full client array is re-encoded with json.MarshalIndent and the whole settings blob is written back via tx.Save (client_inbound_apply.go:417, 443);
  • SyncInbound deletes 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 with CreateInBatches(links, 200) (client_link.go:190-194). It is called with GetClients(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_inbounds row deletions plus 40,000 re-insertions (about 200 multi-row INSERT statements), around 200 chunked SELECTs, 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:

  • addInboundClient takes 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 at client_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.
  • The transaction body runs on one global goroutine. runSerializedTx submits to the single traffic-writer queue (internal/web/service/traffic_writer.go:126-130, one consumer started at traffic_writer.go:41-63), which is shared with the @every 5s traffic poll (AddTraffic -> submitTrafficWrite, internal/web/service/inbound_traffic.go:28-34; cadences at internal/web/web.go:292 and :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:

journalctl -u x-ui --no-pager | grep -F 'Error in adding client on'
grep -F 'Error in adding client on' /var/log/x-ui/3xui.log

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-ui and the panel file is 3xui.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 text traffic writer queue full in 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.AddClient resolves the tag (a cache miss adds a second round trip via refreshRemoteIDs, remote.go:299-310) and then POSTs panel/api/clients/add on 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 own SyncInbound over 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, sets push = false, and falls back to the dirty flag plus ReconcileNode on the @every 5s node sync job (client_inbound_apply.go:506-519; internal/web/job/node_traffic_sync_job.go:366-381, nodeReconcileTimeout 30 s at :21). advancePushedInbound is 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: TestAddDelClientPostgresScale seeds one inbound and issues one AddInboundClient against 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: getAllEmailSubIDs now runs once per create, not once per inbound (client_crud.go:196), so its jsonb_array_elements expansion over ~40,000 entries is paid once. On Postgres the statement is:

SELECT (client.value ->> 'email') AS email, (client.value ->> 'subId') AS sub_id
FROM inbounds, jsonb_array_elements(inbounds.settings::jsonb -> 'clients') AS client(value);

(assembled at internal/web/service/inbound.go:485-490 from internal/database/dialect.go:18-23). What would be decisive instead is pg_stat_statements for one create, filtered to client_inbounds — specifically the calls, rows and total_exec_time of the DELETE FROM "client_inbounds" WHERE inbound_id = $1 and the corresponding multi-row INSERT. 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 SyncInbound on ordinary CRUD (removes the O(total edges) term), narrowing the lockInbound hold 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_statements rows come back.

This reply was generated automatically. A maintainer may follow up.

<!-- gh-comment-id:5329627475 --> @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 at `remote.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.Create` loops over `payload.InboundIds` and calls `addInboundClient` once per inbound (`internal/web/service/client_crud.go:202-224`). Each iteration, for an inbound holding N clients: - `compactOrphans` runs `ceil(N/400)` chunked `SELECT ... WHERE email IN (...)` (`client_inbound_apply.go:412`, `client_locks.go:41-91`); - the full client array is re-encoded with `json.MarshalIndent` and the whole `settings` blob is written back via `tx.Save` (`client_inbound_apply.go:417`, `443`); - `SyncInbound` deletes 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 with `CreateInBatches(links, 200)` (`client_link.go:190-194`). It is called with `GetClients(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_inbounds` row deletions plus 40,000 re-insertions (about 200 multi-row `INSERT` statements), around 200 chunked `SELECT`s, 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: - `addInboundClient` takes 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 at `client_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. - The transaction body runs on one global goroutine. `runSerializedTx` submits to the single traffic-writer queue (`internal/web/service/traffic_writer.go:126-130`, one consumer started at `traffic_writer.go:41-63`), which is shared with the `@every 5s` traffic poll (`AddTraffic` -> `submitTrafficWrite`, `internal/web/service/inbound_traffic.go:28-34`; cadences at `internal/web/web.go:292` and `: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: ``` journalctl -u x-ui --no-pager | grep -F 'Error in adding client on' grep -F 'Error in adding client on' /var/log/x-ui/3xui.log ``` 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-ui` and the panel file is `3xui.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 text `traffic writer queue full` in 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.AddClient` resolves the tag (a cache miss adds a second round trip via `refreshRemoteIDs`, `remote.go:299-310`) and then POSTs `panel/api/clients/add` on 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 own `SyncInbound` over 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, sets `push = false`, and falls back to the dirty flag plus `ReconcileNode` on the `@every 5s` node sync job (`client_inbound_apply.go:506-519`; `internal/web/job/node_traffic_sync_job.go:366-381`, `nodeReconcileTimeout` 30 s at `:21`). `advancePushedInbound` is 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: `TestAddDelClientPostgresScale` seeds one inbound and issues one `AddInboundClient` against 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: `getAllEmailSubIDs` now runs once per create, not once per inbound (`client_crud.go:196`), so its `jsonb_array_elements` expansion over ~40,000 entries is paid once. On Postgres the statement is: ```sql SELECT (client.value ->> 'email') AS email, (client.value ->> 'subId') AS sub_id FROM inbounds, jsonb_array_elements(inbounds.settings::jsonb -> 'clients') AS client(value); ``` (assembled at `internal/web/service/inbound.go:485-490` from `internal/database/dialect.go:18-23`). What would be decisive instead is `pg_stat_statements` for one create, filtered to `client_inbounds` — specifically the `calls`, `rows` and `total_exec_time` of the `DELETE FROM "client_inbounds" WHERE inbound_id = $1` and the corresponding multi-row `INSERT`. 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 `SyncInbound` on ordinary CRUD (removes the O(total edges) term), narrowing the `lockInbound` hold 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_statements` rows come back. *This reply was generated automatically. A maintainer may follow up.*
Author
Owner

@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.

<!-- gh-comment-id:5331030786 --> @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.
Author
Owner

@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!

<!-- gh-comment-id:5333335882 --> @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!
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
MHSanaei/3x-ui#4245
No description provided.