If we build a backend service, we probably need to keep any statistics related to our service such as number of requests, average time for processing, number of errors, etc. We may also need to have statistic records in several time precisions for example hourly and daily. The simplest solution, we can just store any information into a table in our database, then calculate the summary when needed or by a request. But, it will cost our system storage and computing resources.
Unlike relational databases or NoSQL that only have CRUD operations in general, Redis operations are related to the type of data that is stored. For example, a list will have push or pop operations, a sorted set will have a ranking, incrementing, or union operation, and so on. For instance for storing request statistics in Redis, we will store statistics of the response time of a backend application. The metrics are minimum time, maximum time, number of responses, and total response time. The last two metrics can be used for calculating the average time to respond. We will also store the statistics for hourly and daily information.
We need several records in sorted sets to store the following information.
- List of starting times of all periods
- Metrics of each period
- Temporary data for aggregating minimum and maximum values
A list of starting times is used to help us to list all metrics records that we have. The record of metrics of each period will be named with starting time of the period.
Our backend application will call a function every time it handles a request with a response time value in milliseconds as the first parameter of the function.
All metrics in a period will be aggregated in a single record directly. Every time the function is called, it will calculate the period based on the calling time and the precision value.
The processes are as follows.
- Calculate starting time of current period
- Store the response time value in temporary records as both minimum and maximum values of response time
- Aggregate data in temporary records with matrics record of the current period
- Increment number of responses and total response time in the matrics record of the current period
For this example, we utilize Node.js with the redis
module. We also need uuid
for generating a random key for temporary records. The implementation is as follows.
function captureStats(responseTime) {
const now = Date.now();
const hourly = 3600 * 1000;
const daily = 24 * 3600 * 1000;
const tempKeyMin = `stats:temp:${uuidv1()}`;
const tempKeyMax = `stats:temp:${uuidv1()}`;
// get starting time of the period
const stimeHourly = Math.floor(now / hourly) * hourly;
const stimeDaily = Math.floor(now / daily) * daily;
// to store starting time of each period
const timesHourlyKey = `stats:times:${hourly}`;
const timesDailyKey = `stats:times:${daily}`;
// to store metrics of each period
const statsHourlyKey = `stats:${hourly}:${stimeHourly}`;
const statsDailyKey = `stats:${daily}:${stimeDaily}`;
redisClient.multi()
.zadd(timesHourlyKey, now, stimeHourly)
.zadd(timesDailyKey, now, stimeDaily)
.zadd(tempKeyMin, responseTime, 'min')
.zadd(tempKeyMax, responseTime, 'max')
.zunionstore(statsHourlyKey, 2, statsHourlyKey, tempKeyMin, 'aggregate', 'min')
.zunionstore(statsHourlyKey, 2, statsHourlyKey, tempKeyMax, 'aggregate', 'max')
.zunionstore(statsDailyKey, 2, statsDailyKey, tempKeyMin, 'aggregate', 'min')
.zunionstore(statsDailyKey, 2, statsDailyKey, tempKeyMax, 'aggregate', 'max')
.zincrby(statsHourlyKey, 1, 'count')
.zincrby(statsDailyKey, 1, 'count')
.zincrby(statsHourlyKey, responseTime, 'sum')
.zincrby(statsDailyKey, responseTime, 'sum')
.expire(tempKeyMin, 10)
.expire(tempKeyMax, 10)
.exec((err, results) => {
// check
});
}
Each metric record will have the following parameters.
- min. The value will be updated by aggregating the latest value in the temporary record with the current value in the metric record using
zunionstore
and theaggregate min
method. - max. The value will be updated by aggregating the latest value in the temporary record with the current value in the metric record using
zunionstore
and theaggregate max
method. - count. The value will be incremented by one in each function call.
- sum. The value will be incremented by the response time value in each function call.
Comments
Post a Comment