Reputation: 497
Problem: Some events take 1/2 minutes to reach client.
Setup: I have a nodejs backend trying to send events using SSE to a React App client, while having nginx as a proxy. Deployed in aws with fargate task and load balancer.
The events eventually reach the client, but take alot of time making it useless for my use case.
Backend Code:
Endpoint to start connection:
handler: async (req, res) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
})
const id = Date.now()
const data = { id, response: res }
emitterList.push(data) // array with the responses
setTimeout(() => {
res.end()
remove(id)
}, 2 * 60 * 1000)
req.on('close', () => { remove(id) })
}
Endpoint to push data to connected clients
emitterList
.forEach(elem => {
try {
console.log('WRITE: ', new Date())
elem.response.write(`data: ${JSON.stringify(data)}`)
elem.response.write(`\n\n`)
} catch(err) {
deadEmitters.push(elem.id)
}
removeDeadEmitters()
Client Code:
const eventSource = new EventSource(`${process.env.REACT_APP_BACKEND_BASE_URL}/emitter/${id}`)
eventSource.onmessage = (e) => { console.log(new Date()) }
Is there any configuration i need to set in nginx?
Upvotes: 2
Views: 1331
Reputation: 497
The solution was to add the header 'X-Accel-Buffering': 'no' in the response.
Upvotes: 3