-
Notifications
You must be signed in to change notification settings - Fork 88
Outbound rate limiting for persistent APPLICATION clients #349
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: develop/2.4
Are you sure you want to change the base?
Changes from all commits
9868947
06c5745
8a06ae1
a194b8e
72601cd
f5a369a
139699d
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| /** | ||
| * Copyright © 2016-2026 The Thingsboard Authors | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
| package org.thingsboard.mqtt.broker.config; | ||
|
|
||
| import lombok.Data; | ||
| import org.springframework.boot.context.properties.ConfigurationProperties; | ||
| import org.springframework.context.annotation.Configuration; | ||
|
|
||
| @Configuration | ||
| @ConfigurationProperties(prefix = "mqtt.rate-limits.application-persisted-messages") | ||
| @Data | ||
| public class ApplicationPersistedMsgsRateLimitsConfiguration { | ||
|
|
||
| private boolean enabled; | ||
| private String clientConfig; | ||
|
|
||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -24,6 +24,7 @@ | |
| import org.thingsboard.mqtt.broker.common.data.ClientSessionInfo; | ||
| import org.thingsboard.mqtt.broker.common.data.SessionInfo; | ||
| import org.thingsboard.mqtt.broker.common.util.TbRateLimits; | ||
| import org.thingsboard.mqtt.broker.config.ApplicationPersistedMsgsRateLimitsConfiguration; | ||
| import org.thingsboard.mqtt.broker.config.ClientsLimitProperties; | ||
| import org.thingsboard.mqtt.broker.config.DevicePersistedMsgsRateLimitsConfiguration; | ||
| import org.thingsboard.mqtt.broker.config.IncomingRateLimitsConfiguration; | ||
|
|
@@ -44,13 +45,16 @@ public class RateLimitServiceImpl implements RateLimitService { | |
| private final OutgoingRateLimitsConfiguration outgoingRateLimitsConfiguration; | ||
| private final TotalMsgsRateLimitsConfiguration totalMsgsRateLimitsConfiguration; | ||
| private final DevicePersistedMsgsRateLimitsConfiguration devicePersistedMsgsRateLimitsConfiguration; | ||
| private final ApplicationPersistedMsgsRateLimitsConfiguration applicationPersistedMsgsRateLimitsConfiguration; | ||
| private final RateLimitCacheService rateLimitCacheService; | ||
| private final ClientsLimitProperties clientsLimitProperties; | ||
|
|
||
| @Getter | ||
| private ConcurrentMap<String, TbRateLimits> incomingPublishClientLimits; | ||
| @Getter | ||
| private ConcurrentMap<String, TbRateLimits> outgoingPublishClientLimits; | ||
| @Getter | ||
| private ConcurrentMap<String, TbRateLimits> applicationPersistedMsgClientLimits; | ||
|
|
||
| @PostConstruct | ||
| public void init() { | ||
|
|
@@ -60,6 +64,9 @@ public void init() { | |
| if (outgoingRateLimitsConfiguration.isEnabled()) { | ||
| outgoingPublishClientLimits = new ConcurrentHashMap<>(); | ||
| } | ||
| if (applicationPersistedMsgsRateLimitsConfiguration.isEnabled()) { | ||
| applicationPersistedMsgClientLimits = new ConcurrentHashMap<>(); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
|
|
@@ -100,6 +107,9 @@ public void remove(String clientId) { | |
| if (outgoingPublishClientLimits != null) { | ||
| outgoingPublishClientLimits.remove(clientId); | ||
| } | ||
| if (applicationPersistedMsgClientLimits != null) { | ||
| applicationPersistedMsgClientLimits.remove(clientId); | ||
| } | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -175,6 +185,21 @@ public boolean isDevicePersistedMsgsLimitEnabled() { | |
| return devicePersistedMsgsRateLimitsConfiguration.isEnabled(); | ||
| } | ||
|
|
||
| @Override | ||
| public boolean tryConsumeApplicationPersistedMsgs(String clientId) { | ||
| if (!applicationPersistedMsgsRateLimitsConfiguration.isEnabled()) { | ||
| return true; | ||
| } | ||
| TbRateLimits rateLimits = applicationPersistedMsgClientLimits.computeIfAbsent( | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is now the third copy of the per-client bucket idiom — |
||
| clientId, id -> new TbRateLimits(applicationPersistedMsgsRateLimitsConfiguration.getClientConfig())); | ||
| return rateLimits.tryConsume(); | ||
| } | ||
|
|
||
| @Override | ||
| public boolean isApplicationPersistedMsgsRateLimitEnabled() { | ||
| return applicationPersistedMsgsRateLimitsConfiguration.isEnabled(); | ||
| } | ||
|
|
||
| @Override | ||
| public long tryConsumeTotalMsgs(long limit) { | ||
| return rateLimitCacheService.tryConsumeTotalMsgs(limit); | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -27,6 +27,7 @@ | |
| import org.thingsboard.mqtt.broker.actors.client.messages.mqtt.MqttDisconnectMsg; | ||
| import org.thingsboard.mqtt.broker.actors.client.state.ClientActorStateInfo; | ||
| import org.thingsboard.mqtt.broker.adaptor.ProtoConverter; | ||
| import org.thingsboard.mqtt.broker.common.data.PersistedPacketType; | ||
| import org.thingsboard.mqtt.broker.common.data.mqtt.MsgExpiryResult; | ||
| import org.thingsboard.mqtt.broker.common.util.ThingsBoardExecutors; | ||
| import org.thingsboard.mqtt.broker.gen.queue.PublishMsgProto; | ||
|
|
@@ -38,6 +39,7 @@ | |
| import org.thingsboard.mqtt.broker.queue.provider.ApplicationPersistenceMsgQueueFactory; | ||
| import org.thingsboard.mqtt.broker.service.analysis.ClientLogger; | ||
| import org.thingsboard.mqtt.broker.service.historical.stats.TbMessageStatsReportClient; | ||
| import org.thingsboard.mqtt.broker.service.limits.RateLimitService; | ||
| import org.thingsboard.mqtt.broker.service.mqtt.MqttMsgDeliveryService; | ||
| import org.thingsboard.mqtt.broker.service.mqtt.PublishMsg; | ||
| import org.thingsboard.mqtt.broker.service.mqtt.persistence.application.data.ApplicationMainProcessingState; | ||
|
|
@@ -81,6 +83,7 @@ | |
| import java.util.concurrent.ExecutorService; | ||
| import java.util.concurrent.Future; | ||
| import java.util.concurrent.TimeUnit; | ||
| import java.util.function.BooleanSupplier; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| @Service | ||
|
|
@@ -112,6 +115,7 @@ public class ApplicationPersistenceProcessorImpl implements ApplicationPersisten | |
| private final ApplicationClientHelperService appClientHelperService; | ||
| private final AppMsgDeliveryStrategy appMsgDeliveryStrategy; | ||
| private final TbMessageStatsReportClient tbMessageStatsReportClient; | ||
| private final RateLimitService rateLimitService; | ||
| private final boolean isDebugEnabled = log.isDebugEnabled(); | ||
|
|
||
| @Value("${queue.application-persisted-msg.poll-interval}") | ||
|
|
@@ -453,6 +457,7 @@ private ApplicationPubRelMsgCtx processMainPack(ApplicationPubRelMsgCtx pubRelMs | |
|
|
||
| List<PersistedMsg> messagesToDeliver = buildMessagesToDeliver(pubRelMsgCtx, clientSessionCtx, persistedMsgCtx, messages, null); | ||
| submitStrategy.init(messagesToDeliver); | ||
| throttleDelivery(clientId, messagesToDeliver, () -> isClientSessionActive(sessionId, clientState)); | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Message expiry is evaluated once in |
||
|
|
||
| if (isDebugEnabled) { | ||
| log.debug("[{}] Starting main pack, {} messages to deliver", clientId, messagesToDeliver.size()); | ||
|
|
@@ -558,6 +563,7 @@ private ApplicationPubRelMsgCtx processSharedPack(ApplicationPubRelMsgCtx pubRel | |
|
|
||
| List<PersistedMsg> messagesToDeliver = buildMessagesToDeliver(pubRelMsgCtx, clientSessionCtx, persistedMsgCtx, messages, subscription); | ||
| submitStrategy.init(messagesToDeliver); | ||
| throttleDelivery(clientId, messagesToDeliver, () -> isJobActive(job)); | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The four new unit tests exercise |
||
|
|
||
| if (log.isTraceEnabled()) { | ||
| log.trace("[{}] Starting shared subscription pack, {} messages to deliver", clientId, messagesToDeliver.size()); | ||
|
|
@@ -731,6 +737,46 @@ private void deliverMessages(ApplicationSubmitStrategy submitStrategy, ClientSes | |
| appMsgDeliveryStrategy.process(submitStrategy, clientSessionCtx); | ||
| } | ||
|
|
||
| void throttleDelivery(String clientId, List<PersistedMsg> messagesToDeliver, BooleanSupplier isActive) { | ||
| if (!rateLimitService.isApplicationPersistedMsgsRateLimitEnabled()) { | ||
| return; | ||
| } | ||
| int remaining = countPublishMsgs(messagesToDeliver); | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| boolean throttled = false; | ||
| while (remaining > 0) { | ||
| if (!isActive.getAsBoolean()) { | ||
| return; | ||
| } | ||
| if (rateLimitService.tryConsumeApplicationPersistedMsgs(clientId)) { | ||
| remaining--; | ||
| } else { | ||
| if (!throttled) { | ||
| throttled = true; | ||
| if (isDebugEnabled) { | ||
| log.debug("[{}] Outbound rate limit reached; pacing delivery of {} remaining message(s) in this pack", clientId, remaining); | ||
| } | ||
| } | ||
| // Reuse the Kafka poll interval as the throttle back-off granularity (intentionally no separate tunable). | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Reusing |
||
| try { | ||
| Thread.sleep(pollDuration); | ||
| } catch (InterruptedException e) { | ||
| Thread.currentThread().interrupt(); | ||
| return; | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private static int countPublishMsgs(List<PersistedMsg> messagesToDeliver) { | ||
| int count = 0; | ||
| for (PersistedMsg msg : messagesToDeliver) { | ||
| if (PersistedPacketType.PUBLISH == msg.getPacketType()) { | ||
| count++; | ||
| } | ||
| } | ||
| return count; | ||
| } | ||
|
|
||
| private void processPubAckInSharedCtx(String clientId, int packetId, String format) { | ||
| Set<ApplicationSharedSubscriptionCtx> contexts = sharedPackProcessingCtxMap.get(clientId); | ||
| if (CollectionUtils.isEmpty(contexts)) { | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The sibling flags in this interface are
isDevicePersistedMsgsLimitEnabled()andisTotalMsgsLimitEnabled(), but this one has an extraRate:isApplicationPersistedMsgsRateLimitEnabled(). Minor, but for a set of methods a caller finds via autocomplete the odd-one-out is a small papercut —isApplicationPersistedMsgsLimitEnabled()would line up with the others.