mardi 10 décembre 2019

Websockets: Triggering an alert on message if value exists in database

I have a simple application that tracks the price of a stock/cryptocurrency via a websocket connection. A user is able to add up to 100 alerts on the price of the stock. The prices at which the user wants alerts are stored in a MongoDB database. If the price crosses the price alert, it should send him an email/text message.

Currently, I have the functionality to stream price data through the websocket as well as allowing the user to add alerts which get inserted into a database.

The part I am stuck on is the design pattern which would allow checking against all the price alerts added within the database every time a message from the websocket comes in. There are some solutions that I thought of that I am describing below.

The main challenge arises in the fact that the price data that is coming in needs to be checked against the database before the next websocket message comes in (which might be a few milliseconds interval).

Solution 1

This would check againt the database every time a message everytime a message came in from the websocket. However, it seems quite inefficient to make a database call everytime a message came in. Not to mention, I am not sure if what happens if the database retrieval starts lagging the rate at which the websocket is receiving messages.

client.on('message', async (data) => {
    const price = data.price
    const priceAlert = await PriceAlert.findOne({ price: price })

    if (priceAlert) {
        // send email/text message to user
    }
})


Solution 2

The next obvious solution I thought of was to retrieve all the alerts in the database and store them in-memory in an array and then check against that array every-time a message comes in. This would probably solve the problem of time efficiency at the expense of saving everything in-memory. Again, however, I am not sure how this scales as the number of users grows since I would be storing a lot of data in-memory in this case.

const priceAlerts = PriceAlert.find({}) // store all price alerts in database in an array

client.on('message', async (data) => {
    const price = data.price

    if (price exists in priceAlerts) { // check if price data that came in is within the array retrieved earlier
        // send email/text message to user
    }
})

Appreciate any feedback and help!

Thank you! :)

Aucun commentaire:

Enregistrer un commentaire