Skip to content

perf(nats): optimize user sync and bound queue processing - #892

Merged
x0sina merged 1 commit into
PasarGuard:pref-boostfrom
DrSaeedHub:perf/nats-sync-optimization
Sep 12, 2026
Merged

x0sina merged 1 commit into
PasarGuard:pref-boostfrom
DrSaeedHub:perf/nats-sync-optimization

Conversation

@DrSaeedHub

Copy link
Copy Markdown
Contributor

Summary

Repeated queue discovery and reconnect cleanup replay historical deletion markers and create JetStream consumers even when little work is pending. Maintain one live key index per worker so initialized idle polls make no NATS requests, and clear node queues using cached candidates plus newer revisions.

  • Fetch initial metadata in batches of 256 and hand off to ordered live updates without losing concurrent changes.
  • Rebuild interrupted snapshots, allow progressing snapshots to finish, and release consumers on completion, cancellation, and shutdown.
  • Bound bulk operations to 32 concurrent requests per store and avoid creating a task for every queued item at once.
  • Expose acknowledged local writes and claims immediately so delayed notifications do not delay discovery or expired-claim recovery.
  • Compact deletion markers older than five minutes on the scheduler leader, preserving concurrent writes and live work.
  • Add regression coverage and restore logger states after test migrations to keep log assertions independent of collection order.

Type of change

  • Bug fix
  • New feature
  • Breaking change
  • Refactor / cleanup
  • Documentation
  • Tests / CI

Checklist

  • I tested the change locally or explained why it cannot be tested.
  • I added or updated tests for behavior changes.
  • I updated documentation, translations, or examples if needed. No user-facing configuration changes.
  • I checked database migrations when models or schema changed. No schema changes.
  • I did not include secrets, tokens, private keys, or unrelated changes.

Testing

With DEBUG=false, TZ=UTC, and NATS_SERVER_BINARY pointing to NATS 2.10.29:

python -m pytest tests/test_nats_kv_index.py tests/test_nats_node_memory.py tests/test_nats_sync_integration.py -q
  • 35 focused tests passed, including four independent worker processes, claim ownership and expiry, delayed notifications, reconnects, server restart, consumer recreation, cancellation, and snapshot-to-live handoff races.
  • Full local SQLite suite: 631 passed, zero skipped, with external network tests enabled.
  • Local stress validation: 3.5 million deletion markers, four readers, no dropped messages, four steady consumers, and zero outgoing requests from initialized idle polls. Twenty subsequent clears received only 60 control responses without replaying old markers.
  • The identical application and test sources passed SQLite, PostgreSQL, TimescaleDB, MySQL, MariaDB, focused NATS tests, lint, and image checks in CI.
  • Consolidated source tree matches the validated source tree exactly; git diff --check passed.

Screenshots

Not applicable.

Notes for reviewers

The index discovers candidate keys only. Authoritative values and claim ownership still use JetStream reads and revision-checked operations. Compaction removes revisions only through an observed deletion marker, protecting concurrently recreated keys.

Bounded snapshots use the KV object's underlying JetStream context because the KV watch API exposes push delivery. Real-server tests cover snapshot lifecycle and ordered live subscription recovery. No database migrations or dependency changes are required.

Reuse live key indexes, replay snapshots in bounded batches, and clear queues from cached keys and recent revisions. Bound bulk operations, safely compact old deletion markers, and preserve claim recovery across delayed notifications and reconnects.

Add concurrency, recovery, compaction, and idle-traffic regression coverage.
@coderabbitai

coderabbitai Bot commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: f4bbfa86-736a-47d5-a0e0-a9d1dae04f05

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@DrSaeedHub DrSaeedHub mentioned this pull request Sep 11, 2026
8 of 11 tasks
@x0sina
x0sina merged commit 03c8b5f into PasarGuard:pref-boost Sep 12, 2026
10 checks passed
x0sina added a commit that referenced this pull request Sep 12, 2026
)

* feat(user): enhance user inbound tag retrieval and subscription update handling

- Improved the `inbounds` method in the User model to efficiently gather inbound tags from enabled groups.
- Updated user subscription update logic to queue updates for background processing, enhancing performance.
- Refactored user status change notifications to streamline the process and ensure accurate user state management.
- Introduced caching for usage coefficients to optimize node user statistics collection.
- Enhanced subscription generation with caching mechanisms for improved performance.

* fix: discard stale subscription updates and align FinalMask test (#886)

* fix: read flushed subscription updates from a fresh snapshot (#888)

* perf(nats): optimize user sync and bound queue processing (#892)

Reuse live key indexes, replay snapshots in bounded batches, and clear queues from cached keys and recent revisions. Bound bulk operations, safely compact old deletion markers, and preserve claim recovery across delayed notifications and reconnects.

Add concurrency, recovery, compaction, and idle-traffic regression coverage.

* test(hosts): match FinalMask noise fixture to Xray array packet

Keep the #889 payload ([1, 2, 255], no rand) so it agrees with the merged assertions after pref-boost picked up both that change and the older #886 sample.

* fix(cleanup): add timeout handling for node-sync key compaction and improve logging

- Introduced asyncio timeout for the compaction process to prevent indefinite blocking.
- Added a warning log for timeout occurrences to ensure visibility of potential issues.
- Updated Cache-Control header in subscription responses to "no-store" for better caching behavior.
- Refactored subscription update buffer to use a drain lock for concurrent flush operations, improving reliability and performance.

---------

Co-authored-by: DrSaeedHub <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants