Concepts / Building Search UI / Improve performance
Oct. 11, 2019

Improve Performance

Mitigate the impact of slow network in your search application.

Algolia is a hosted search API. This means that if the network is slow, the search experience will be impacted. In this guide, you will see how to make the perception of search better even if the network shows some downtime.

Adding a loading indicator

Imagine a user using your search in a subway, by default this is the kind of experience they will get:

  • type some characters
  • nothing happens
  • still waiting, still nothing

At this point, the user is really wondering what is happening. You can start enhancing this experience by providing a visual element to hint that something is happening: a loading indicator.

And for this, InstantSearch.js provides an option in the searchBox called showLoadingIndicator. The indicator will appear in the searchBox. It will also be triggered a little after the last query has been sent to Algolia. This prevents the element to flicker.

The delay can be configured using the stalledSearchDelay on the instantSearch constructor.

Here is an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
const search = instantsearch({
  indexName: 'instant_search',
  stalledSearchDelay: 200, // this is the default value for the delay
  searchClient,
});

search.addWidgets([
  instantsearch.widgets.searchBox({
    container: '#searchBox',
    placeholder: 'Search for products',
    showLoadingIndicator: true, // this add the loading indicator
  })
]);

Make your own loading indicator

The mechanism of the searchbox loading indicator is also available to other widgets. Here, you’ll see how to make a custom widget that changes based on the loading conditions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const search = instantsearch({
  indexName: 'instant_search',
  searchClient,
});

// The container that we want to use has to in the page
const loadingContainer = document.querySelector('#loading');

search.addWidgets([{
  render: ({ searchMetadata = {} }) => {
    const { isSearchStalled } = searchMetadata;

    loadingContainer.innerHTML = isSearchStalled ? 'loading' : '';
  },
}]);

This example shows how to make a custom widget that writes “loading” when the search is stalled and nothing otherwise. Because of the delay introduced, users with optimal conditions will not be bothered by the message. If the user is not searching in those conditions, we provide some information about what is going on underneath.

Debouncing

Another way of thinking about performance perception is to try to prevent some of the lagging effect. The InstantSearch experience generates one query per keystroke. While this is normally desirable, in the worst of conditions this can lead to congestion because browsers can only make a limited amount of requests in parallel. By reducing the amount of requests done, we can prevent this effect.

Debouncing is a way to limit the number of requests and avoid processing non-necessary ones by avoiding sending requests before a timeout.

There is no built-in solution to debounce in InstantSearch.js. You can implement it at the searchBox level though with the queryHook option. Here is an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const search = instantsearch({
  indexName: 'instant_search',
  searchClient,
});

let timerId;

search.addWidgets([
  instantsearch.widgets.searchBox({
    container: document.querySelector('#searchBox'),
    placeholder: 'Search for products',
    queryHook(query, refine) {
      clearTimeout(timerId);
      timerId = setTimeout(() => refine(query), 500);
    },
  })
]);

This function uses the option queryHook. This function is called every time a keystroke has to be made. In this case, the code debounces the call to refine.

Optimize build size

If you are using Webpack 2+ or Rollup as build system, you are elligible for tree shaking.

Optimize your build with tree shaking

With InstantSearch.js, you need to use the files that prepared with tree-shaking in mind. Those files are located in the /es sub-package. To be optimal, you also want to import only what you’re actually using rather than the whole library.

1
2
3
4
5
6
7
8
9
10
11
12
13
// instantsearch() function without reference to the widgets or connectors
import instantsearch from 'instantsearch.js/es';

// import connectors individually
import { connectSearchBox } from 'instantsearch.js/es/connectors';

// import widgets individually
import { searchBox } from 'instantsearch.js/es/widgets';

const search = instantsearch({ ... });

search.addWidgets([searchBox({ ... })]);
search.addWidgets([connectSearchBox(() => { ... })({ ... })])

Caching

Caching by default (and how to get rid of it)

By default, Algolia caches the search results of the queries, storing them locally in the cache. If the user ends up entering a search (or part of it) that has already been entered previously, the results will be retrieved from the cache, instead of requesting them from Algolia, making the application much faster. Note that the cache is an in-memory cache, which means that it only persist during the current page session. As soon as the page reloads the cache is cleared.

While it is a very convenient feature, in some cases it is useful to have the ability to clear the cache and make a new request to Algolia. For instance, when changes are made on some records on your index, you might want the frontend side of your application to be updated to reflect that change (in order to avoid displaying stale results retrieved from the cache).

To do so, there is a method on the instantsearch instance called refresh(). When the method is called, it clears the cache and triggers a new search.

There are two different use cases where you would want to discard the cache:

  • your application data is being directly updated by your users (for example, in a dashboard). In this use case you would want to refresh the cache based on some application state such as the last modification from the user.
  • your application data is being updated by another process that you don’t manage (for example a CRON job that updates users inside Algolia). For this you might want to periodically refresh the cache of your application.

Refresh the cache triggered by an action from the user

If you know that the cache needs to be refreshed conditionally after a specific event, then you can trigger the refresh based on a user action (adding a new product, clicking on a button for instance).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const search = instantsearch({
  indexName: 'demo_ecommerce',
  searchClient,
});

search.addWidgets([
  instantsearch.widgets.searchBox({
    container: '#searchbox',
  })
]);

search.addWidgets([
  instantsearch.widgets.hits({
    container: '#hits',
  })
]);

document.querySelector('button').addEventListener('click', () => {
  search.refresh();
});

search.start();

You can also check out the live example. You can find the source code of the example on GitHub.

Refresh the cache periodically

You also have the option to setup an given period of time that will determine how often the cache will be cleared. This method will ensure that the cache is cleared on a regular basis. You should use this approach if you cannot use a user action as a specific event to trigger the clearing of the cache.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const search = instantsearch({
  indexName: 'demo_ecommerce',
  searchClient,
});

search.addWidgets([
  instantsearch.widgets.searchBox({
    container: '#searchbox',
  }),

  instantsearch.widgets.hits({
    container: '#hits',
  })
]);

setInterval(() => {
  search.refresh();
}, 5000);

search.start();

Note that if you need to wait for an action from Algolia, you should use waitTask to avoid refreshing the cache too early. Check out the live example. You can find the source code of the example on GitHub.

Queries Per Second (QPS)

Search operations are limited by the maximum QPS (the allowed number of queries performed per second) of the plan.

Every time you press a key in InstantSearch using the searchBox, we count one operation. Then, depending on the widgets you will be adding to your search interface, you may have more operations being counted on each keystroke. For example, if you have a search made out of a searchBox, a menu, and a refinementList, then every keystroke will trigger one operation. But as soon as a user refines the menu or refinementList, it will trigger a second operation on each keystroke.

A good rule to keep in mind is that most search interfaces using InstantSearch will trigger one operation per keystroke. Then every refined widget (clicked widget) will add one more operation to the total count.

In case you have issue with the QPS you can consider implement a debounced searchBox.

Did you find this page helpful?