0

I am trying to generate random requestId for my express server. I have been using uuidV1() from node-uuid module. It's working fine for the normal requests but when i'm trying to loadtest it using concurrent requests. the generated value is same.

const uuidv1 = require("uuid/v1");    
const reqId  = uuidv1() 

3 Answers3

1

You should generate it in a middleware and attach it to the request object. Secondly uuidv1 generates ids based on timestamps(check wiki uuid), use v4 instead. following is the express example.

const express = require('express');
const app = express();
const uuidv4 = require("uuid/v4");    

app.use((req, res, next) => {
    req.reqId = uuidv4();
    next();
});

app.get('/', function (req, res) {  
  res.send(`Hello World! with reqId: ${req.reqId}`);
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
});
  • on using loadtest npm module with, it generate same uuid if you'll put concurrency to more than 1. example: loadtest -n 10 -c 5, in this way the generated reqId is coming duplicate – Divyanshu Srivastava Jan 07 '20 at 09:49
  • putting some snippets of how you are using this(your web server). would be helpful in order to answer – Abhishek Chandel Jan 07 '20 at 10:03
  • for above example I loadtest it using `ab -n 20 -c 15 http://localhost:3000/`. which is sending 15 concurrent request, and I saw no duplication in reqId. If you are using mac ab(apache benchmark) should be installed by default – Abhishek Chandel Jan 07 '20 at 10:39
0

Instead of uuid module. you can use below module https://www.npmjs.com/package/uniqid

With this you can generate unique id based on combination of mac address, process id and timestamp

bhushan629
  • 13
  • 4
0

The 'express-request-id' npm module should do the work for you. https://www.npmjs.com/package/express-request-id

const express = require('express');
const app = express();
const addRequestId = require('express-request-id')();  

app.use(addRequestId);

app.get('/', function (req, res) {  
  res.send(`Request Id : ${req.id}`);
});

app.listen(3000, function () {
  console.log('listening on port 3000')
});