0

I have a fastify server that's pointing to two "backend" fastify servers and I'd like to generate a random number that is then used to decide which backend to route to.

Currently it only works the first time, and I'm unable to override the upstream afterwards.

server.register(require('fastify-http-proxy'), {
  upstream: '',
  replyOptions: { 
    getUpstream: (originalReq, base) => {
      if (Math.random() < 0.5) {
        console.log(`setting base to backend1`)
        return `http://localhost:${backend1Port}`
      } else {
        console.log(`setting base to backend2`)
        return `http://localhost:${backend2Port}`
      }
    },
    disableCache: true,
    cacheURLs: 0,
  },
})

How can I make it so that upon refresh it might change where it routes to?

  • Do you see the console.log() statements every time you refresh? Are you saying it's hitting the "other" conditional branch but not update the path? – Alexander Staroselsky Nov 18 '21 at 20:50
  • Yes I see it every time I refresh. It looks like this: setting base to backend2 hitting backend2 setting base to backend1 hitting backend2 – Patrick Hwang Nov 18 '21 at 22:04
  • And then you no longer see any console.log statements when it's running? – Alexander Staroselsky Nov 18 '21 at 22:20
  • Sorry, I should specify that I'm going to localhost:3000 and refreshing there (not rerunning node server.js), so I see the console.log statements every time I refresh the web page while running node. I get the same effect when doing curl – Patrick Hwang Nov 18 '21 at 22:35

1 Answers1

0

Figured it out. disableCache needed to be outside of replyOptions.

server.register(require('fastify-http-proxy'), {
  upstream: '',
  replyOptions: { 
    getUpstream: (originalReq, base) => {
      if (Math.random() < 0.5) {
        console.log(`setting base to backend1`)
        return `http://localhost:${backend1Port}`
      } else {
        console.log(`setting base to backend2`)
        return `http://localhost:${backend2Port}`
      }
    },
    disableCache: true,
    cacheURLs: 0,
  },
})