{"id":28047867,"url":"https://github.com/Envek/sidekiq-fair_tenant","last_synced_at":"2025-05-11T21:05:02.094Z","repository":{"id":216783997,"uuid":"742410376","full_name":"Envek/sidekiq-fair_tenant","owner":"Envek","description":"Sidekiq middleware to re-route “greedy” clients’ jobs to slower queues","archived":false,"fork":false,"pushed_at":"2024-04-01T15:45:13.000Z","size":18,"stargazers_count":77,"open_issues_count":1,"forks_count":2,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-05-08T00:08:32.691Z","etag":null,"topics":["fairness","multitenancy","sidekiq"],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Envek.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-01-12T12:18:02.000Z","updated_at":"2025-04-22T08:44:34.000Z","dependencies_parsed_at":"2024-01-12T21:27:01.670Z","dependency_job_id":"d9561e40-1199-49ca-9034-8b02a7d2a355","html_url":"https://github.com/Envek/sidekiq-fair_tenant","commit_stats":{"total_commits":3,"total_committers":2,"mean_commits":1.5,"dds":"0.33333333333333337","last_synced_commit":"b738dd155b3d5c5f5417b8aeb47c19b497192fa4"},"previous_names":["envek/sidekiq-fair_tenant"],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Envek%2Fsidekiq-fair_tenant","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Envek%2Fsidekiq-fair_tenant/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Envek%2Fsidekiq-fair_tenant/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Envek%2Fsidekiq-fair_tenant/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Envek","download_url":"https://codeload.github.com/Envek/sidekiq-fair_tenant/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253633120,"owners_count":21939389,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["fairness","multitenancy","sidekiq"],"created_at":"2025-05-11T21:05:01.132Z","updated_at":"2025-05-11T21:05:02.080Z","avatar_url":"https://github.com/Envek.png","language":"Ruby","funding_links":[],"categories":["Ruby"],"sub_categories":[],"readme":"# Sidekiq::FairTenant\n\nThrottle “greedy” clients’ jobs to ensure more or less fair distribution of resources between clients.\n\nThis tiny [Sidekiq] middleware will re-route client's jobs after certain threshold to throttled queues (defined by you), where they will be processed with reduced priority.\n\n“Weighted queues” feature of Sidekiq allows to de-prioritize jobs in throttled queues, so they will not block jobs from other clients, at the same time preserving overall throughput.\n\n\u003ca href=\"https://evilmartians.com/?utm_source=sidekiq-fair_tenant\"\u003e\n  \u003cpicture\u003e\n    \u003csource\n      media=\"(prefers-color-scheme: dark)\"\n      srcset=\"https://evilmartians.com/badges/sponsored-by-evil-martians_v2.0_for-dark-bg@2x.png\"\n    \u003e\n    \u003cimg\n      src=\"https://evilmartians.com/badges/sponsored-by-evil-martians_v2.0@2x.png\"\n      alt=\"Sponsored by Evil Martians\"\n      width=\"236\"\n      height=\"54\"\n    \u003e\n  \u003c/picture\u003e\n\u003c/a\u003e\n\n## Installation\n\n 1. Install the gem and add to the application's Gemfile by executing:\n\n    ```sh\n    bundle add sidekiq-fair_tenant\n    ```\n\n 2. Add `fair_tenant_queues` section to `sidekiq_options` in your job class:\n\n    ```diff\n     class SomeJob\n       sidekiq_options \\\n         queue: 'default',\n    +    fair_tenant_queues: [\n    +     { queue: 'throttled_2x', threshold: 100, per: 1.hour },\n    +     { queue: 'throttled_4x', threshold:  10, per: 1.minute },\n    +    ]\n     end\n    ```\n\n 3. Add tenant detection login into your job class:\n\n    ```diff\n     class SomeJob\n    +  def self.fair_tenant(*_perform_arguments)\n    +    # Return any string that will be used as tenant name\n    +    \"tenant_1\"\n    +  end\n     end\n    ```\n\n 4. Add throttled queues with reduced weights to your Sidekiq configuration:\n\n    ```diff\n     # config/sidekiq.yml\n     :queues:\n       - [default, 4]\n    +  - [throttled_2x, 2]\n    +  - [throttled_4x, 1]\n    ```\n\n    See [Sidekiq Advanced options for Queues](https://github.com/sidekiq/sidekiq/wiki/Advanced-Options#queues) to learn more about queue weights.\n\n## Usage\n\n### Specifying throttling rules\n\nIn your job class, add `fair_tenant_queues` section to `sidekiq_options` as array of hashes with following keys:\n\n - `queue` - throttled queue name to re-route jobs into.\n - `threshold` - maximum number of jobs allowed to be enqueued within `per` seconds.\n - `per` - sliding time window in seconds to count jobs (you can use ActiveSupport Durations in Rails).\n\nYou can specify multiple rules and they all will be checked. _Last_ matching rule will be used, so order rules from least to most restrictive.\n\nExample:\n\n```ruby\nsidekiq_options \\\n  queue: 'default',\n  fair_tenant_queues: [\n    # First rule is less restrictive, reacting to a large number of jobs enqueued in a long time window\n    { queue: 'throttled_2x', threshold: 1_000, per: 1.day },\n    # Next rule is more restrictive, reacting to spikes of jobs in a short time window\n    { queue: 'throttled_4x', threshold:    10, per: 1.minute },\n  ]\n```\n\n### Specifying tenant\n\n 1. Explicitly during job enqueuing:\n\n    ```ruby\n    SomeJob.set(fair_tenant: 'tenant_1').perform_async\n    ```\n\n 2. Dynamically using `fair_tenant` class-level method in your job class (receives same arguments as `perform`)\n\n    ```ruby\n    class SomeJob\n      def self.fair_tenant(*_perform_arguments)\n        # Return any string that will be used as tenant name\n        \"tenant_1\"\n      end\n    end\n    ```\n\n 3. Set `fair_tenant` job option in a custom [middleware](https://github.com/sidekiq/sidekiq/wiki/Middleware) earlier in the stack.\n\n 4. Or let this gem automatically pick tenant name from [apartment-sidekiq](https://github.com/influitive/apartment-sidekiq) if you're using apartment gem.\n\n## Configuration\n\nConfiguration is handled by [anyway_config] gem. With it you can load settings from environment variables (which names are constructed from config key upcased and prefixed with `SIDEKIQ_FAIR_TENANT_`), YAML files, and other sources. See [anyway_config] docs for details.\n\n| Config key                 | Type     | Default                                                             | Description                                                                                                                                                                                                             |\n|----------------------------|----------|---------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `max_throttling_window`    | integer  | `86_400` (1 day)                                                    | Maximum throttling window in seconds                                                                                                                                                                                    |\n| `enqueues_key`             | string   | `sidekiq-fair_tenant:enqueued:%\u003cjob_class\u003es:tenant:%\u003cfair_tenant\u003es` | Ruby [format string](https://docs.ruby-lang.org/en/3.3/format_specifications_rdoc.html) used as a name for Redis key holding job ids for throttling window. Available placeholders: `queue`, `job_class`, `fair_tenant` |\n| `logger`                   | logger   | `Sidekiq.logger`                                                    | Logger instance used for warning logging.                                                                                                                                                                               |\n\n## How it works\n\nIf number of jobs enqueued by a single client exceeds some threshold per a sliding time window, their jobs would be re-routed to another queue, with lower priority.\n\nThis gem tracks single client's jobs in a Redis [sorted set](https://redis.io/docs/data-types/sorted-sets/) with job id as a key and enqueuing timestamp as a score. When a new job is enqueued, it is added to the set, and then the set is trimmed to contain only jobs enqueued within the last `max_throttling_window` seconds.\n\nOn every enqueue attempt, the set is checked for number of jobs enqueued within the last `per` seconds of every rule. If the number of jobs in this time window exceeds `threshold`, the job is enqueued to a throttled queue, otherwise it is enqueued to the default queue. If multiple rules match, last one is used.\n\nYou are expected to configure Sidekiq to process throttled queues with lower priority using [queue weights](https://github.com/mperham/sidekiq/wiki/Advanced-Options#queues).\n\n### Advantages\n - If fast queues are empty then slow queues are processed at full speed (no artificial delays)\n - If fast queues are full, slow queues are still processed, but slower (configurable), so application doesn’t “stall” for throttled users\n - Minimal changes to the application code are required.\n\n### Disadvantages\n - As Sidekiq does not support mixing ordered and weighted queue modes (as stated in Sidekiq Wiki on queue configuration), you can’t make the same worker process execute some super important queue always first, ignoring other queues. Run separate worker to solve this.\n - You have to keep track of all your queues and their weights.\n\n## Development\n\nAfter checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.\n\nTo install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).\n\n## Contributing\n\nBug reports and pull requests are welcome on GitHub at https://github.com/Envek/sidekiq-fair_tenant.\n\n## License\n\nThe gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).\n\n[sidekiq]: https://github.com/sidekiq/sidekiq \"Simple, efficient background processing for Ruby\"\n[anyway_config]: https://github.com/palkan/anyway_config \"Configuration library for Ruby gems and applications\"\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FEnvek%2Fsidekiq-fair_tenant","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FEnvek%2Fsidekiq-fair_tenant","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FEnvek%2Fsidekiq-fair_tenant/lists"}