├── .gitignore
├── LICENSE
├── README.md
├── consumer-java
├── pom.xml
└── src
│ └── main
│ └── java
│ └── org
│ └── apache
│ └── pulsar
│ └── client
│ └── impl
│ ├── ReferenceMultiTopicsConsumerImpl.java
│ ├── WeightedConsumerBuilder.java
│ ├── WeightedMultiTopicsConsumerImpl.java
│ └── weight
│ ├── ExponentialWeightDistribution.java
│ ├── LinearWeightDistribution.java
│ ├── RangeDistribution.java
│ ├── TopicMessageCountTracker.java
│ ├── TopicThresholdDistribution.java
│ ├── TopicThresholdDistributionImpl.java
│ ├── WeightDistribution.java
│ └── WeightedConsumerConfiguration.java
├── docs
└── images
│ ├── lagging_backlog.png
│ ├── lagging_thpt.png
│ └── tailing_thpt.png
└── examples
├── pom.xml
└── src
└── main
├── java
└── examples
│ ├── StatPrinter.java
│ └── UnorderedConsumptionJob.java
└── resources
└── log4j2.xml
/.gitignore:
--------------------------------------------------------------------------------
1 | ### Maven template
2 | target/
3 | pom.xml.tag
4 | pom.xml.releaseBackup
5 | pom.xml.versionsBackup
6 | pom.xml.next
7 | release.properties
8 | dependency-reduced-pom.xml
9 | buildNumber.properties
10 | .mvn/timing.properties
11 | # https://github.com/takari/maven-wrapper#usage-without-binary-jar
12 | .mvn/wrapper/maven-wrapper.jar
13 |
14 | ### JetBrains
15 | *.iml
16 | *.ipr
17 | *.iws
18 | /.idea/
19 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Pulsar Weighted Consumer (PWC)
2 |
3 | This repository provides implementation of a pulsar consumer that can do priority consumption across multiple topics. Topics and associated weights are supplied during consumer creation. The unequal consumption is done on a best effort basis and is best observed when all the input topics have sufficient backlog.
4 |
5 | > Note: `WeightedMultiTopicsConsumerImpl` is a fork of the MultiTopicsConsumerImpl that ships with java pulsar-client. A neat extension of the same class is not possible at this moment since we need to change certain private members.
6 |
7 | ## Adding PWC to your build
8 |
9 | ### Dependency and Versioning
10 | [Pulsar java client](https://pulsar.apache.org/docs/client-libraries-java/) should be added as a dependency in the maven project where you intend to import PWC. PWC builds are published follows a versioning scheme aligned with Pulsar: `major.minor-X`, where major.minor should be the same as the included pulsar client. Since pulsar clients are fully compatible across versions, it should be possible to use a different pulsar-client as compared to PWC, but this is neither tested nor recommended.
11 |
12 | A good strategy would be to look at the PWC builds already available and align your pulsar-client to one of those versions.
13 | ```xml
14 |
15 | com.flipkart.viesti
16 | pulsar-weighted-consumer
17 | 2.7-1
18 |
19 | ```
20 |
21 | If you have a hard requirement of using a specific version of pulsar-client, but PWC has not been published for that pulsar verion, feel free to open a ticket.
22 |
23 | ### Snapshots
24 |
25 | Snapshots of PWC are published using version as `major.minor-SNAPSHOT`. For example: `com.flipkart:pulsar-weighted-consumer:2.7-SNAPSHOT`
26 |
27 | ### Artifactory and Releases
28 |
29 | Maven/Gradle releases are published to [clojars artifactory here](https://clojars.org/com.flipkart/pulsar-weighted-consumer). You need to have clojars repository added in your build file. Example for pom:
30 | ```xml
31 |
32 |
33 | clojars
34 | Clojars repository
35 | https://clojars.org/repo
36 |
37 |
38 | ```
39 |
40 | You can also find more information about [changelog and releases here](https://github.com/flipkart-incubator/pulsar-weighted-consumer/releases).
41 |
42 | TODO: javadocs link
43 |
44 | ## Learn about PWC
45 |
46 | ### Concepts
47 |
48 | Pulsar weighted consumer modifies the original multi topic consumer and introduces unequal consumptions of messages across different topics. Multi topic consumer of Pulsar works by creating multiple topic specific consumers and draining messages from each of them to a shared queue. This shared queue in turn is drained by the user using `receive` method variants. PWC introduces few changes like keeping count of messages in the shared queue at a topic granularity and assigning weighted thresholds to the topics. Note that here a threshold or count is cumulatively applied to all partitions of a topic. When the message count breaches the topic's threshold, fetch of messages from its internal sub-consumer is paused. To ensure adherence to weights, it remains paused unless all the messages from the shared queue have not been drained (this is configurable though).
49 |
50 | #### Bounds and Weights
51 |
52 | The thresholds are determined by `minBound` which is associated with the lowest weighted topic and `maxBound` associate with the highest weighted topic. The thresholds for rest of the topics are calculated using the `distributionStrategy` specified. Consider an example of `minBound=100, maxBound=1000, distributionStrategy=LINEAR` and 5 topics associated with weights 1 to 5, respectively. Here the thresholds for the topics get computed as: `[100, 325, 550, 775, 1000]` which is essentially a linear increment of 225 messages between consecutive weights. Users can tweak minBound, maxBound, distributionStrategy and weights to arrive at the relative thresholds for messages of different topics in the shared queue. More the messages of a given topic in the shared queue, higher the consumption throughput for that topic (not true everytime though, refer to force priority consumption section).
53 |
54 | > **NOTE**
55 | > If w_max and w_min are the highest and lowest weights that you assign to the topics and if `w_max - w_min < 10`, it is recommended to not change the minBound and maxBound defaults.
56 |
57 | #### Bursting
58 |
59 | Although the fetch of messages from subconsumer is paused, the subconsumer can continue to fetch messages independently over the network from the broker, as per its receiver queue size. Since network I/O is significantly costlier than the local subconsumer to main consumer fetch, the pause of an internal topic consumer does not introduce a measurable penalty.
60 |
61 | The above design becomes relevant when you have few high throughput topics of lesser priority (smaller threshold) in tandem with low throughput topics of higher priority. What we do not want is a behaviour where high throughput topics are artificially penalized and overall consumption rate to remain low despite the consumer having capacity to process more messages. PWC exhibits the behaviour of bursting where if high priority topics do not have enough messages available, overall consumption rate does not suffer and lower priority topics can burst.
62 |
63 | #### Force Priority Consumption
64 |
65 | A side effect of having support for bursting is that when you have enough messages to consume across all topics and message processing is near instantaneous on the local consumer (think of printing message or incrementing a counter and subsequently acking), then all the topics regardless of weights assigned will show a high and near-equal consumption rate. This may be the desired behaviour in majority of the situations where weights do no matter much if local message processing is much faster than the cost to fetch the messages in the first place over the network.
66 |
67 | But if in situations like above, strict priority consumption is required, then a separate flag `throttleReceieverQueue` can be enabled which applies weighted thresholds even to the messages fetched by specific topic consumers from the brokers. Usage of this flag should only be done in very specific scenarios, and you are almost always better off leaving this untouched because once you turn this on, it disables bursting.
68 |
69 | ### Example Usage
70 |
71 | Instead of using the default consumer builder like `pulsarClient.newConsumer()...`, you would instantiate an instance of WeightedConsumerBuilder, configure all the weight related flags and then configure rest of the subscription specific properties.
72 |
73 | ```java
74 | Map topicWeights = new HashMap() {{
75 | put("persistent://abc-tenant/xyz-ns/topic1", 1);
76 | put("persistent://abc-tenant/xyz-ns/topic2", 2);
77 | put("persistent://abc-tenant/xyz-ns/topic3", 3);
78 | }};
79 |
80 | WeightedConsumerBuilder consumerBuilder = new WeightedConsumerBuilder<>(client, Schema.BYTES)
81 | .distributionStrategy(WeightedConsumerConfiguration.DistributionStrategy.EXPONENTIAL)
82 | .topics(topicWeights);
83 |
84 | Consumer consumer = consumerBuilder
85 | .subscriptionName("sub-a")
86 | .subscriptionType(SubscriptionType.Shared) //all subscription types are supported
87 | .subscriptionInitialPosition(SubscriptionInitialPosition.Earliest)
88 | .subscribe();
89 | ```
90 |
91 | The consumer behaviour is 100% backwards compatible and all the subscription or client related configuration flags are available. Any topic that is added through older overloads like `topics(String...)` defaults to weight=1. Use of the newer overload `topics(Map)` is strongly recommended.
92 |
93 | ### Configuration
94 |
95 | Different weight related flags have been introduced which can be configured through WeightedConsumerBuilder.
96 |
97 | | Method | Default | Description |
98 | |-------------------------------|---------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
99 | | topics(Map) | | Map of topics and associated weights. Weight has to be in the range [1,maxWeightAllowed]. Topic names can follow a suffix convention with weight included in the names, like so: `persistent://public/default/hello-world-weight-2`. Here the weight is parsed as 2. Precedence order: weight override supplied in the map > weight specified in the name > 1 (if weight cannot be determined) |
100 | | maxWeightAllowed(int) | 100 | Default should be good enough in most of the circumstances |
101 | | minBound(int) | 100 | Minimum number of messages to be fetched for a topic in the shared queue. Applies to the lowest weighted topic Default should be good enough in most of the circumstances |
102 | | maxBound(int) | 1000 | Maximum number of messages to be fetched for a topic in the shared queue. Applies to the highest weighted topic. Also used to set the receiver queue size for all internal consumers. Existing receiver queue size property of subscription is ignored. Default should be good enough in most of the circumstances |
103 | | distributionStrategy(enum) | LINEAR | Determines how bounds/thresholds are distributed between lowest weighted and highest weighted topic. Available values: LINEAR, EXPONENTIAL |
104 | | retryTopicWeight(int) | 1 | Assign a weight to the retry topic as configured in the retry topic policies of the consumer |
105 | | throttleReceiveQueue(boolean) | false | Do not switch to `true` unless you understand why. Refer to Concepts#Force Priority Consumption to understand this flag better. Default is good enough for almost all circumstances. |
106 | | queueResumeThreshold(int) | 0 | Caution! Do not change this flag unless you understand why. Refer to Concepts to understand how shared queue and thresholds interact. Default is good enough for almost all circumstances. |
107 |
108 | ## Test Results
109 |
110 | Topics and subscriptions were setup like so:
111 | * 3 topics (4 partitions each) with weights [1,2,3] respectively
112 | * Enough backlog of messages was present in the topics for testing lagging consumers. Tailing consumer tests were done with zero backlog.
113 | * 1 "shared" subscription per topic using PWC with minBound=100, maxBound=1000, distribution=LINEAR
114 |
115 | ### Lagging consumers
116 |
117 | * Messages were processed in parallel across 4 worker threads.
118 | * Message processing time was simulated to be 5ms.
119 | * Unequal consumption rate across subs of different topics was observed.
120 | * Subsequently, backlog was observed to reduce at different rates for each sub.
121 |
122 | 
123 | 
124 |
125 | ### Tailing consumers
126 |
127 | * Messages were processed in parallel across 4 worker threads.
128 | * Message processing was near instantaneous (no simulated delay)
129 | * All subs are able to keep up with the produce rate. This demonstrates bursting in consumption rate of lower weighted topics when message processing can keep up.
130 |
131 | 
132 |
133 | ## How to develop?
134 |
135 | ### Branching and Release Strategy
136 |
137 | * The repository follows branching strategy as `branch-major.minor` where major.minor aligns with the pulsar versions.
138 | * `main` branch corresponds typically with the latest pulsar release and used for development purposes. Releases are done from specific branches.
139 | * Bug fixes specific to a pulsar version can be done in the relevant branch.
140 | * Patches which apply to all pulsar versions can be merged directly to `main` and cherry-picked to other branches for release.
141 |
142 | ### How to do code contributions?
143 |
144 | Start a PR from your fork with the base branch set correctly. Base branch should be master if this is a new feature or a bug fix that affects the latest version. Base branch can be specific pulsar version branch like `branch-2.7` if this a hotfix for a specific release. PR should cover the following aspects:
145 |
146 | * Clarifies the purpose and the need of this change. In case of a bug, ensure you have clearly documented the affected library version, jdk version, stack traces, logs and reproduction steps (if applicable).
147 | * In case of a non-trivial design change, the PR description should explain that succintly and attach test results for the key test cases (mentioned elsewhere in the doc) to ensure there has been no regression.
148 | * Inline comments for non obvious behaviour or in case of a hacky workaround as well as README doc changes should be included in the PR is applicable.
149 | * Backwards compatibility of client facing behaviour should be adhered to.
150 |
--------------------------------------------------------------------------------
/consumer-java/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | com.flipkart
8 | pulsar-weighted-consumer
9 | 2.10-0
10 |
11 |
12 | 8
13 | 2.10.0
14 |
15 |
16 |
17 |
18 | The Apache Software License, Version 2.0
19 | http://www.apache.org/licenses/LICENSE-2.0.txt
20 |
21 |
22 |
23 |
24 |
25 | clojars
26 | Clojars repository
27 | https://clojars.org/repo
28 |
29 |
30 |
31 |
32 |
33 | clojars
34 | Clojars repository
35 | https://clojars.org/repo
36 |
37 |
38 | central
39 | Maven Central
40 | https://repo1.maven.org/maven2/
41 |
42 |
43 |
44 |
45 |
46 |
47 | org.apache.maven.plugins
48 | maven-compiler-plugin
49 |
50 | ${java.version}
51 | ${java.version}
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 | org.apache.pulsar
60 | pulsar-client
61 | ${pulsar.version}
62 | provided
63 |
64 |
65 |
66 |
--------------------------------------------------------------------------------
/consumer-java/src/main/java/org/apache/pulsar/client/impl/ReferenceMultiTopicsConsumerImpl.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *