Repository navigation
Conversation
| job = job.job | ||
| if job.concurrency_key: | ||
| cursor.execute( | ||
| self._push_concurrency_config_sql(), |
There was a problem hiding this comment.
I've got some concerns about doing this per-job - if users are doing this the "right" way they may be batching tens of thousands of jobs at a time, which is going to issue an extra query per job with a concurrency_key. IMO we should be gathering up all the unique concurrency keys and issuing 1 bulk upsert.
Alternatively, and which might be better, we should require the user to call a function to push a concurrency rule before they take effect - a concurrency_key with no rule set would just be ignored when fetching jobs. This way we can remove this upsert here entirely and never have to process individual jobs as they get inserted.
There was a problem hiding this comment.
You're right for the bulk insert, would be easy to do. Should we insert the jobs as one bulk insert as well ?
I went on this implementation because I found the API simpler for the user but maybe you're wright that might be clearer to push ahead of time a concurrency rule.
There was a problem hiding this comment.
The think is, having a table with concurrency keys as rows that can be locked the time to fetch jobs in workers looks like the easiest way to implement concurrency and avoid race conditions. On job push is the first moment we know the full concurrency key when using a partition id.
We could use a trigger too if we do not support methods as concurrency key. If we use a bulk insert for jobs, the trigger would be more performant as it avoid a round trip.
There was a problem hiding this comment.
I have implemented deduplication of concurrency key and bulk insert. Performance should be fine even when inserting a high number of jobs.
| Concurrency | ||
| ----------------------- | ||
|
|
||
| Control the number of jobs that can run simultaneously using concurrency: |
There was a problem hiding this comment.
We should probably reword this a bit to make it clear immediately that this impacts global concurrency. I see you've got the note down below but it's the core reason to use this. Something like:
"Control the number of jobs with the same concurrency key that can run simultaneously across all workers and queues using with_concurrency():"?
There was a problem hiding this comment.
I have added more documentation about how concurrency is implemented and the why on the choice of the solution.
| await cursor.execute( | ||
| sql.SQL( | ||
| """ | ||
| CREATE TABLE {concurrency_configs} ( |
There was a problem hiding this comment.
I'm worried about high cardinality in the concurrency_key (like <func_name>_<user ID>), it might quickly result in a lot of rows. But, that gotcha might just need to be documented to be A-OK.
There was a problem hiding this comment.
To avoid the table to increase infinitely, we could have the pruner plugin to clean this table on a regular basis.
There was a problem hiding this comment.
I have extended the pruner plugin to prune new concurrency_configs table.
|
Update: work is still ongoing. Need to find some time. |
9e04bf0 to
92fa930
Compare
|
Hey @TkTech, I have found the time to go on with the work after thinking extensively about it. Tradeoffs I did:
I looked at how other products implement global concurrency.
None of these 2 alternatives looked easy and fit into Chancy current architecture, so I decided to go for resolving concurrency limits when fetching jobs. It has downsides for sure:
Please tell me what you think about this work and if you could see it in chancy in the future ? Thanks again for all the work on chancy ! EDIT: |
|
Hy @TkTech, Please let me know if you disagree with the choices I have done or there are any adjustments or further testing you'd like me to do—I'm happy to refine the code based on your feedback. Thanks for all your work on the project!" |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## 26_ux #50 +/- ##
==========================================
+ Coverage 81.68% 84.06% +2.38%
==========================================
Files 68 70 +2
Lines 4051 4877 +826
==========================================
+ Hits 3309 4100 +791
- Misses 742 777 +35
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
Can't see anything I'd disagree with right off the bat. Two of the windows tests stalled out, I've just rerun them to see if it was spurious or a code issue. |
|
Hm, we're consistently deadlocking on two of the tests. I don't particularly think this is an issue with your change (it might be coming from v0.26) but I'll need to hunt it down. |
|
Hi @TkTech, I merged
|
- Rule.to_sql takes an optional context everywhere, including the workflow pruning rule (ruff 0.16 B006). - ruff format on the concurrency and pruner tests.
151abbc to
ad6e053
Compare
Job now has its own docstring, so autodoc no longer renders its dataclass signature with annotations (unparseable <factory> defaults), and the cron docs point at BaseJob.unique_key, where the attribute is now defined.
There was a problem hiding this comment.
🟡 Changes recommended
Job claiming remains race-prone, and several persistence and pruning paths can strand or misconfigure jobs.
8 open findings
Reuse one evaluated concurrency key per job · New Use backward-compatible deserialization for missing concurrency fields · New Require configs to be old and orphaned before deletion · New Lock base job rows to prevent duplicate claims · New Preserve or reject callable concurrency key serialization · New Preserve the deprecated prune method and subclass overrides · New Bound orphaned concurrency-config deletion per pruning pass · New Persist queue tuning values in declarations and migration · New
What changed in this PR
Adds global per-job and per-partition concurrency limits backed by PostgreSQL locking and configurable queue scanning.
Changes:
- Adds concurrency rules, persistence, migration, and worker enforcement.
- Adds concurrency-config pruning and queue scan tuning.
- Adds documentation and integration tests.
| File | Description |
|---|---|
chancy/__init__.py |
Exports ConcurrencyRule. |
chancy/app.py |
Persists concurrency configs and job keys. |
chancy/job.py |
Defines concurrency rules and job serialization. |
chancy/migrations/v9.py |
Adds concurrency schema and index. |
chancy/plugins/cron/__init__.py |
Updates job API reference. |
chancy/plugins/pruner.py |
Prunes jobs and concurrency configs. |
chancy/plugins/workflow/__init__.py |
Updates rule SQL signature. |
chancy/queue.py |
Adds scan-window settings. |
chancy/rule.py |
Adds concurrency pruning rules. |
chancy/worker.py |
Enforces concurrency during job fetching. |
docs/howto/jobs.rst |
Documents concurrency and scan tuning. |
tests/plugins/test_pruner.py |
Tests concurrency-config pruning. |
tests/test_concurrency.py |
Tests concurrency behavior and key evaluation. |
🧠 Review effort: Balanced
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| "max_attempts": job.max_attempts, | ||
| "scheduled_at": job.scheduled_at, | ||
| "unique_key": job.unique_key, | ||
| "concurrency_key": job.evaluate_concurrency_key(), |
| concurrency_rule=ConcurrencyRule.deserialize(data["c"]) | ||
| if data["c"] | ||
| else None, |
| DEFAULT_CONCURRENCY_RULE = ( | ||
| ConcurrencyRules.Age() > 60 * 60 * 24 * 7 | ||
| ) | ConcurrencyRules.Orphaned() |
| SELECT rj.id, rj.priority | ||
| FROM ranked_jobs rj | ||
| WHERE | ||
| -- Non-constrained jobs are always eligible | ||
| rj.concurrency_key IS NULL | ||
| OR | ||
| -- Constrained jobs must be within available slots | ||
| (rj.concurrency_key IS NOT NULL AND rj.job_rank <= rj.slots_available) | ||
| ORDER BY rj.priority DESC, rj.id ASC | ||
| LIMIT %(maximum_jobs_to_fetch)s | ||
| FOR UPDATE SKIP LOCKED |
| def serialize(self) -> dict: | ||
| # Would be great to access global logger here to warn about callable not being serializable | ||
| return { | ||
| "k": self.key if not callable(self.key) else None, | ||
| "v": self.max, | ||
| } |
| ): | ||
| with timed_block() as chancy_time: | ||
| rows_removed = await self.prune(chancy, cursor) | ||
| job_rows_removed = await self.prune_jobs(chancy, cursor) |
| config_query = sql.SQL( | ||
| """ | ||
| DELETE FROM {concurrency_configs} | ||
| WHERE ({rule}) | ||
| """ |
| scan_factor: int = 20 | ||
| #: The maximum number of jobs to scan when fetching work, regardless of | ||
| #: the scan_factor calculation. | ||
| scan_limit_upper_bound: int = 1000 |
|
Thanks for the work on this. This'll need closer review - it'll target a release after 0.26. |
|
Thanks for all your work on this. I've tried to use it as the foundation but unfortunately the performance impact of this approach is unavoidable and reduces queue operations by about 75%, as well as some isolation issues that can allow the limit to be exceeded. I have iterated off of this and tried several different approaches and do have a working slot-based approach which is nearly on-par with regular, non-limited queues and has better contention performance. It'll be available with v0.28. |


Hey @TkTech,
I worked on an implementation to enforce global concurrency by job and partition before the case of rate limiting as it is more useful for my team and it looks easier.
I tried designing a SQL query in
fetch_jobsthat respects global concurrency and would still be performant. It is not perfect though as there is the edge case where a lot of jobs subject to concurrency constraint could block a queue but it gives us ground for discussion.I liked your idea of faking it using temporary queues too. Maybe we could use this for rate limiting ? I have the intuition we can solve the concurrency problem in SQL and stay performant.