Fedir Petryk
Fedir Petryk

Reputation: 497

Netty: How to limit websocket channel messages per second?

I need to limit messages received on websocket channel per second for netty server. Could'n find any ideas how to do that.

Any ideas would be appreciated

Thank you

Upvotes: 0

Views: 538

Answers (1)

Dmitriy Dumanskiy
Dmitriy Dumanskiy

Reputation: 12857

You need to add simple ChannelInboundHandlerAdapter handler to your pipeline and add the simple counter to channelRead(ChannelHandlerContext ctx, Object msg) method. I would recommend you to use some of CodaHale Metrics Class for that purpose.

Pseudo code:

private final QuotaLimitChecker limitChecker;

public MessageDecoder() {
    this.limitChecker = new QuotaLimitChecker();
}


@Override 
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (limitChecker.quotaReached(100)) { //assume limit is 100 req per sec
        return;
    }
}

Where QuotaLimitChecker is a class that increments counter and checks if the limit is reached.

public class QuotaLimitChecker {

    private final static Logger log = LogManager.getLogger(QuotaLimitChecker.class);

    private final int userQuotaLimit;
    //here is specific implementation of Meter for your needs
    private final InstanceLoadMeter quotaMeter;

    public QuotaLimitChecker(int userQuotaLimit) {
        this.userQuotaLimit = userQuotaLimit;
        this.quotaMeter = new InstanceLoadMeter();
    }

    public boolean quotaReached() {
        if (quotaMeter.getOneMinuteRate() > userQuotaLimit) {
            log.debug("User has exceeded message quota limit.");
            return true;
        }
        quotaMeter.mark();
        return false;
    }

}

Here is my implementation of QuotaLimitChecker that uses the simplified version Meter class of CodaHale Metrics library.

Upvotes: 2

Related Questions