Update your website with zero downtime

Blog


author small image Siva Kishore G
Posted : 19 Jan 2022
Modified : 06 Jun 2022
Expert Developers

Introduction

This article is for developers with full stack experience. Big enterprises like amazon, ebay, uber, and expedia dont use CMS like WordPress or Joomla. They have their own thing. If you are building something of such grade, then these techniques will help you implement real time website updates.

Update website in real time

Why is it necessary?

Certain niches as shown below require dealing with real time prices & updates to the websites. This is where the user expects automatic updates.

  • Hotel booking
  • Car rental business
  • Ecommerce
  • Delivery business like
    • Uber
    • Ola
    • Uber eats
    • Zomato
    • Swiggy
  • Stock market
  • Crypto market

Technologies required

  • Nginx

    Nginx (pronounced Engine Ex) is an open source lightweight web server. It's best for reverse proxying, caching and load balancing etc. It's my choice of server since it beats the old school Apache in all aspects. It employs asynchronous event-driven architecture and handles requests in a single thread, providing a high level of concurrency with very little memory usage.

    Configure your nginx server block with these two lines to updgarde it to support websockets

    location / {
       proxy_set_header Upgrade $http_upgrade; # add this line
       proxy_set_header Connection "upgrade"; # add this line
    }
  • WebSockets

    These power chat frameworks are everywhere, and they are not just tied to chats alone, you can actually use them to update your website. The end user can see the updates instantaneously. We will be using Socket.io and generally used for admin triggered updates. Learn More

  • WebWorkers

    Web workers run in their own thread. Any smooth running website will need 60fps and if you have a lot of JS code that deals with calculations, time intervals, timeouts, etc then you will see the page being unresponsive. Webworkers can offload these from the main thread and enhance site performance. We will use this for user triggered updates, meaning the user will request the update in contract to the above admin triggered updates. Learn More

  • Crude (Not recommended)

    Using JS's setInterval you can check with the server for the updates. But this method is not efficient. I've seen beginners use this kind of technique, and it might work well while developing. But when the site opens for the public and gets substantial traffic it will come to a grinding halt. A very bad user experience!

Scenarios


Ecommerce website

Lets say, you are designing an ecommerce website, something like amazon. You have multiple sellers updating the product on your website. Some of them are running time based promotions, some of them are adding new items. The user visits the page and leaves it open on his / her device. When the user checks back in, the price stays the same unless the user reloads the page.

Flight Booking

There could be many people looking at the same flight but the seats are limited. It doesn't make sense to hold the seats for whoever is on the website. Some might drop out right at the end without paying; some might be just checking the price. Whatever the reason may be, they need to be notified of price changes in real time.

Solution - 1

Simply reload the page after a certain timeout. This is the easiest way to update the page but it's not efficient and users might get distracted. It's not a good user experience. Browsers act differently when the user is not on the page. The time elapsed can be much greater if the user has navigated to a different tab.

setTimeout( function(){
  window.location.reload()
}, 5*60*1000)
Crude Method

To overcome this, we need to take the help of web workers, assuming they are compatible with the browser. If not, you may have to fallback to the crude method.

// worker.js
setTimeout( function(){
  postMessage("Reload the page")
}, 5*60*1000 )
// page.js
if (typeof(Worker) !== "undefined") {
  // Browser supports
  var reloadWorker = new Worker("worker.js");
  reloadWorker.onmessage = function(event){
    window.location.reload()
  }
} else {
  // Browser Doesn't support
  // Dont use this method unless you absolutely need it
  setTimeout( function(){
    window.location.reload()
  }, 5*60*1000)
  // Instead, notify the user and have him/her reload the page manually
  // Also implement "Countdown timer" on the page
}

Solution - 2

Socket IO to rescue. These can be directly used in the page.js file. No need for web workers.

Consider the ecommerce scenario where multiple users are on a particular product page. The seller wants to update the price right away. This is where we need to implement socket io and let the admin emit an update event (programatically speaking). The server will listen to this event and in turn emits another event that will broadcast the message to all the users (whoever is on that page). And on the user page, the socket will listen to that particular event and update the price accordingly.

const io = require('socket.io')({
  // Use cors if the chat server is different from the webserver
  cors: {
    origin: "*",
    methods: ["GET", "PUT", "POST"]
  }
});

io.on('connection', socket => {
  socket.on('update-authorized-from-admin', productObj => {
     socket.broadcast.emit(productObj.product_id,productObj.price)
  })
})
// admin.js
var socket = io("https://mychatserver.com");
function broadcastPrice(product_id, value){
  socket.emit('update-authorized-from-admin', {product_id,value})
}
// user.js
var socket = io("https://mychatserver.com");
socket.on('product_id', () => {
  updateProductPrice()
})

It would be nice to notify the user about the price update. Feel free to use our simple notification templates

Q Working Exercise

Now that you understand the logic, take it to the next step and work on a more complex scenario.

How did amazon implement the time based promotions. The timer clocks down no matter what, reload the page, navigate to pricing page etc. What if the user is in the middle of payment processing and the offer expires?

Post your thoughts in the comment section below!



Post a comment

I promise, I keep it clean *

Comments

Alert SVG Cookie Consent

This website uses cookies and similar technologies, to enhance your browsing experience and provide personalized recommendations. By continuing to use our website, you agree to our Privacy policy.