How Algolia Reduces Latency For 21B Searches Per Month

19,875
Algolia
Developer-friendly hosted search service. API clients for all major frameworks and languages. REST, JSON & detailed documentation.

By Josh Dzielak, Developer Advocate at Algolia.


Algolia Paris meeting room


Algolia helps developers build search. At the core of Algolia is a built-from-scratch search engine exposed via a JSON API. In February 2017, we processed 21 billion queries and 27 billion indexing operations for 8,000+ live integrations. Some more numbers:

  • Query volume: 1B/day peak, 750M/day average (13K/s during peak hours)
  • Indexing operations: 10B/day peak, 1B/day average (spikes can be over 1M/s)
  • Number of API servers: 800+
  • Total memory in production: 64TB
  • Total I/O per day: 3.9PB
  • Total SSD storage capacity: 566TB

We’ve written about our stack before and are big fans of StackShare and the community here. In this post we‘ll look at how our stack is designed from the ground up to reduce latency and the tools we use to monitor latency in production.

I’m Josh and I’m a Developer Advocate at Algolia, formerly the VP Engineering at Keen IO. Being a developer advocate is pretty cool. I get to code, write and speak. I also get to converse daily with developers using Algolia.

Frequently, I get asked what Algolia’s API tech stack looks like. Many people are surprised when I tell them:

  1. The Algolia search engine is written in C++ and runs inside of nginx. All searches start and finish inside of our nginx module.

  2. API clients connect directly to the nginx host where the search happens. There are no load balancers or network hops.

  3. Algolia runs on hand-picked bare metal. We use high-frequency CPUs like the 3.9Ghz Intel Xeon E5–1650v4 and load machines with 256GB of RAM.

  4. Algolia uses a hybrid-tenancy model. Some clusters are shared between customers and some are dedicated, so we can use hardware efficiently while providing full isolation to customers who need it.

  5. Algolia doesn’t use AWS or any cloud-based hosting for the API. We have our own servers spanning 47 datacenters in 15 global regions.


Algolia architecture diagram


Why this infrastructure?

The primary design goal for our stack is to aggressively reduce latency. For the kinds of searches that Algolia powers—suited to demanding consumers who are used to Google, Amazon and Facebook—latency is a UX killer. Search-as-you-type experiences, which have become the norm since Google announced instant search in 2011, have demanding requirements. Any more than 100ms from end-to-end can be perceived as sluggish, glitchy and distracting. But at 50ms or less the experience feels magical. We prefer magic.

Monitoring

Our monitoring stack helps us keep an eye on latency across all of our clusters. We use Wavefront to collect metrics from every machine. We like Wavefront because it’s simple to integrate (we have it plugged in to StatsD and collectd), provides good dashboards, and has integrated alerting.

We use PagerDuty to fire alerts for abnormalities like CPU depletion, resource exhaustion and long-running indexing jobs. For non-urgent alerts, like single process crashes, we dump and collect the core for further investigation. If the same non-urgent alert repeats more than a set number of times, we do trigger a PagerDuty alert. We keep only the last 5 core dumps to avoid filling up the disk.

When a query takes more than 1 second we send an alert into Slack. From there, someone on our Core Engineering Squad will investigate. On a typical day, we might see as few as 1 or even 0 of these, so Slack has been a good fit.

Probes

We have probes in 45 locations around the world to measure the latency and the availability of our production clusters. We host the probes with 12 different providers, not necessarily the same as where our API servers are. The results from these probes are publicly visible at status.algolia.com. We use a custom internal API to aggregate the large amount of data that probes fetch from each cluster and turn it into a single value per region.


Algolia probes


Downed Machines

Downed machines are detected within 30 seconds by a custom Ruby application. Once a machine is detected to be down, we push a DNS change to take it out of the cluster. The upper bound of propagation for that change is 2 minutes (DNS TTL). During this time, API clients implement their internal retry strategy to connect to healthy machines in the cluster, so there is no customer impact.

Debugging Slow Queries

When a query takes abnormally long - more than 1 second - we dump everything about it to a file. We keep everything we need to rerun it including the application ID, index name and all query parameters. High-level profiling information is also stored - with it, we can figure out where time is spent in the heaviest 10% of query processing. A syscall called getrusage analyzes resource utilization of the calling process and its children.

For the kernel, we record the number of major page faults (ru_majflt), number of block inputs, number of context switches, elapsed wall clock time (using gettimeofday, so that we don’t skip counting time on a blocking I/O like a major page fault since we’re using memory mapped files) and a variety of other statistics that help us determine the root cause.

With data in hand, the investigation proceeds in this order:

  1. The hardware
  2. The software
  3. Operating system and production environment

Hardware

The easiest problem to detect is a hardware issue. We see burned SSDs, broken memory modules and overheated CPUs. We automate the reporting of the most common failures like SSDs by alerting on S.M.A.R.T. data. For infrequent errors, we might need to run a suite of specific tools to narrow down the root cause, like mbw for uncovering memory bandwidth issues. And of course, there is always syslog which logs most hardware failures.

Individual machine failures will not have a customer impact because each cluster has 3 machines. Where it’s possible in a given geographical region, each machine is located in a different datacenter and attached to a different network provider. This provides further insulation from network or datacenter loss.

Software

We have some close-to-zero cost profiling information obtained from the getrusage syscall. Sometimes that’s enough to diagnose an issue with the engine code. If not, we need to look to profiling. We can’t run a profiler in production for performance reasons, but we can do this after the fact.

An external binary is attached to a profiler, containing exactly the same code as the module running inside of nginx. The profiler uses information obtained by google-perftools, a very accurate stack-sampling profiler, to simulate the exact conditions of the production machine.

OS / Environment

If we can rule out hardware and software failure, the problem might have been with the operating environment at that point in time. That means analyzing system-wide data in the hope of discovering an anomaly.

Once we discovered that defragmentation of huge pages in the kernel could block our process for several hundred milliseconds. This defragmentation isn’t necessary because we keep large memory pools like nginx. Now we make sure it doesn’t happen, to the benefit of more consistent latency for all of our customers.

Deployment

Every Algolia application runs on a cluster of 3 machines for redundancy and increased throughput. Each indexing operation is replicated across the machines using a durable queue.

Clusters can be mirrored to other global regions across Algolia’s Distributed Search Network (DSN). Global coverage is critical for delivering low latency to users coming from different continents. You can think of DSN like a CDN without caching - every query is running against a live, up-to-date copy of the index.

Early Detection

When we release a new version of the code that powers the API, we do it in an incremental, cluster-aware way so we can rollback immediately if something goes wrong.

Automated by a set of custom deployment scripts, the order of the rolling deploy looks like this:

  • Testing machines
  • Staging machines
  • ⅓ of production machines
  • Another ⅓ of production machines
  • The final ⅓ of production machines

First, we test the new code with unit tests and functional tests on a host that with an exact production configuration. During the API deployment process we use a custom set of scripts to run the tests, but in other areas of our stack we’re using Travis CI.

One thing we guard against is a network issue that produces a split-brain partition during a rolling deployment. Our deployment strategy considers every new version as unstable until it has consensus from every server, and it will continue to retry the deploy until the network partition heals.

Before deployment begins, another process has encrypted our binaries and uploaded them to an S3 bucket. The S3 bucket sits behind CloudFlare to make downloading the binaries fast from anywhere.

We use a custom shell script to do deployments. The script launches the new binaries and then checks to make sure that the new process is running. If it’s not, the script assumes that something has gone wrong and automatically rolls back to the previous version. Even if the previous version also can’t come up, we still won’t have a customer impact while we troubleshoot because the other machines in the cluster can still service requests.

Scaling

For a search engine, there are two basic dimensions of scaling:

  • Search capacity - how many searches can be performed?
  • Storage capacity - how many records can the index hold?

To increase your search capacity with Algolia, you can replicate your data to additional clusters using the point-and-click DSN feature. Once a new DSN cluster is provisioned and brought up-to-date with data, it will automatically begin to process queries.

Scaling storage capacity is a bit more complicated.

Multiple Clusters

Today, Algolia customers who cannot fit on one cluster need to provision a separate cluster and create logic at the application layer to balance between them. This is often needed by SaaS companies who have customers growing at different rates, and sometimes one customer can be 10x or 100x compared to the others, so you need to move that customer to somewhere they can fit.

Soon we’ll be releasing a feature that takes this complexity behind the API. Algolia will automatically balance data a customer’s available clusters based on a few key pieces of information. The way it works is similar to sharding but without the limitation of shards being pinned to a specific node. Shards can be moved between clusters dynamically. This avoids a very serious problem encountered by many search engines - if the original shard key guess was wrong, the entire cluster will have to be rebuilt down the road.

Collaboration

Our humans and our bots congregate on Slack. Last year we had some growing pains, but now we have a prefix-based naming convention that works pretty well. Our channels are named #team-engineering, #help-engineering, #notif-github, etc.. The #team- channels are for members of a team, #help- channels are for getting help from a team, and #notif- channels are for collecting automatic notifications.


Algolia Zoom Room


It would be hard to count the number of Zoom meetings we have on a given day. Our two main offices are in Paris and San Francisco, making 7am-10am PST the busiest time of day for video calls. We now have dedicated "Zoom Rooms" with iPads, high-resolution cameras and big TVs that make the experience really smooth. With new offices in New York and Atlanta, Zoom will become an even more important part of our collaboration stack which also includes Github, Trello and Asana.

Team

When you're an API, performance and scalability are customer-facing features. The work that our engineers do directly affects the 15,000+ developers that rely on our API. Being developers ourselves, we’re very passionate about open source and staying active with our community.


Algolia values


We’re hiring! Come help us make building search a rewarding experience. Algolia teammates come from a diverse range of backgrounds and 15 different countries. Our values are Care, Humility, Trust, Candor and Grit. Employees are encouraged to travel to different offices - Paris, San Francisco, or now Atlanta - at least once a year, to build strong personal connections inside of the company.

See our open positions on StackShare.

Questions about our stack? We love to talk tech. Comment below or ask us on our Discourse forum.

Thanks to Julien Lemoine, Adam Surak, Rémy-Christophe Schermesser, Jason Harris and Raphael Terrier for their much-appreciated help on this post.

Algolia
Developer-friendly hosted search service. API clients for all major frameworks and languages. REST, JSON & detailed documentation.
Tools mentioned in article
Open jobs at Algolia
Partner Engineer - Remote
Atlanta | New York | San Francisco |
The Algolia Partner Engineering Team plays a vital role in growing our partner network of systems integrator, digital agencies and 3rd party platforms and ISVs to develop technical integration. As a Partner Engineer, your job will require not only technical mastery of Algolia's suite of offerings, but also the ability to disseminate this knowledge externally. You will be empowering our partners to first understand our products and then to build similar solutions in the future. This is a highly autonomous role in which no one day will be the same as the last.
  • Act as the onboarding and technical engagement manager to ensure the partner receives clear and timely communications and understands Algolia products from a technical level 
  • Enable partners to be successful by guiding them through the implementation process, designing and performing on-site trainings, and encouraging them to become certified
  • Guide our technology partners to build bridges between Algolia and their products (personalisation solution, visual or voice search, ecommerce platform,...)
  • Act as the technical counterpart to our Partner Executives: join calls, help answer technical questions during the partner discovery phase, and craft services strategies
  • Provide meaningful feedback to our internal product team based on the needs of your partners and their clients
  • Contribute to processes, documentation, and tooling to ensure the team can scale efficiently
  • 5+ years professional experience as a web developer
  • Proficient in Javascript and at least one back-end language; willingness to dive into and potentially learn additional languages as needs arise
  • 3+ years experience in a client-facing or education role
  • Excellent written and oral English skills
  • Preference for candidates with experience at our current stage and beyond (over 10,000 customers, $50-200M ARR range, high growth, lots of change and building internal infrastructure).
  • Experience at our current stage and beyond ($50-200M ARR range, high growth, lots of change and building internal infrastructure) 
  • Prior experience working for a digital agency or systems integrator
  • Prior experience in education or public speaking
  • Knowledge of UX / UI design and an understanding of common tools (Sketch, Photoshop, etc.)
  • Background in the search industry
  • Computer Science Degree
  • GRIT - Problem-solving and perseverance capability in an ever-changing and growing environment
  • TRUST - Willingness to trust our co-workers and to take ownership 
  • CANDOR - Ability to receive and give constructive feedback.
  • CARE - Genuine care about other team members, our clients and the decisions we make in the company.
  • HUMILITY- Aptitude for learning from others, putting ego aside.
  • Covered medical, dental, and vision benefits for you and your family 
  • 401(k) Matching Plan
  • Flexible work hours and unlimited Paid Time Off 
  • Paid Parental Leave
  • Pre-tax commuter benefits 
  • Life insurance and disability benefits
  • Competitive pay and stock options
  • Charitable contribution matching 
  • Fully stocked kitchens
  • Catered lunches on Tuesdays and Thursdays 
  • Workout Wednesdays w/ personal trainer 
  • Bi-monthly meditation sessions 
  • Senior Cloud Engineer Azure - SRE
    Paris | Bucarest | London
    *These roles are open to full and partial remote from France, Romania and Czech Republic.* You have most likely used Algolia in the last week without even knowing about it. What about joining the team and enabling more developers to build great search experiences with little worry about the reliability of their search engine? Site Reliability Engineers (SRE) at Algolia are both software and systems engineers that ensure we can reliably serve billions of queries every day, for users all around the world, despite datacenters being unavailable and undersea cables being cut. As we operate many services including our Search API, Places, DocSearch and Analytics, you’ll keep learning new things everyday and share what you have learned. The platform we develop uses both virtual and bare-metal systems spanning over 50 datacenters in 17 different regions serving millions of users from every corner of the globe. Since search is a critical component of many applications, the SRE team maintains a high level of expertise in system failures in order to prevent them and provide reliable service to our customers. No two problems are the same because all the systems evolve all the time. We expect you to be a resilient problem solver who isn’t afraid to think outside of the box and use the knowledge of system interactions in your favor. You’ll also take ownership of complete projects and execute them. The team is composed of engineers with different backgrounds and experience both in the industry and academia. The diversity works in our favour and you should increase it by bringing your experience, your knowledge and your point of view. Thinking differently is a plus, not a minus. We’re transparent with each other and to other teams both about our success and our failures. This way we learn, we accept our weaknesses and continuously strive to improve both personally and professionally.
  • Work with other teams to identify, troubleshoot, and resolve high impact issues
  • Evaluate performance of current and future systems, both software and hardware
  • Participate in design of new systems
  • Develop and maintain the automation tools used for all systems
  • Participate in on-call rotation to ensure fast response to production issues
  • Ensure that the Infrastructure best practices are followed
  • Be a team player 
  • Microsoft Azure certifications (about Architecture, Infrastructure, Deployment or Administration)
  • 2+ years of software engineering experience
  • 1+ year of Azure production experience
  • Knowledge of Shell scripting and at least one scripting language (Python, Ruby, etc.)
  • Willing to learn Go (golang)
  • Understanding of Linux systems: I/O, process scheduling, filesystems
  • Understanding of computer networks: TCP/IP, DNS, load-balancing
  • Excellent spoken and written English skills required
  • Rigor in high code quality, automated testing and other engineering best practices
  • Ability to make independent decisions and taking ownership for them 
  • Experience at our current stage and beyond ($50-200M ARR range, high growth, lots of change and building internal infrastructure).
  • Knowledge of another Cloud platforms (AWS or GCP)
  • Knowledge of Go (golang)
  • Knowledge of automated integration tests
  • Knowledge of Chaos engineering
  • Ability to use a configuration management tool like Ansible, Puppet or Chef
  • Knowledge of low level principles of computers and network components
  • Performance profiling of applications both in development and production 
  • GRIT - Problem-solving and perseverance capability in an ever-changing and growing environment.
  • TRUST - Willingness to trust our co-workers and to take ownership.
  • CANDOR - Ability to receive and give constructive feedback.
  • CARE - Genuine care about other team members, our clients and the decisions we make in the company.
  • HUMILITY- Aptitude for learning from others, putting ego aside. 
  • Private Medical Insurance
  • Life and Disability Insurance
  • Business Travel Insurance
  • Relocation support
  • Company Canteen (high standard)
  • Flexible work hours and flexible time off 
  • Competitive pay and equity
  • Coaching and sponsorship to participate and speak at leading industry conferences
  • Ongoing professional education opportunities through internal & external workshops, including public speaking, language learning (English/French)
  • Fun: we spend time together — team building, socializing and making tools that encourage getting to know teammates across offices and continents
  • Charitable contribution matching
  • Unique referral rewards program: refer a candidate, and we’ll donate to your charity of choice
  • Fully stocked kitchens
  • Team workouts
  • Meals & happy hours 
  • Tech Lead Front-end - DX Chapter
    Paris | London |
    Algolia was built to help users deliver an intuitive search-as-you-type experience on their websites and mobile apps. We provide a search API used by thousands of customers in more than 100 countries. Billions of search queries are answered every month thanks to the code we push every day into production. We're looking for a Tech Lead Front-end to join the Developer Experience (DX) team at Algolia, onsite from the Paris office or in partial/full remote from France and the UK. We are responsible for providing the best developer experience to our users through the development of open source UI libraries such as InstantSearch.js. InstantSearch libraries are sitting on top of the raw Algolia API, providing UI semantics that are easy to use and understand, like a SearchBox UI component to add to your webpage. We're not using only one framework, but all of them (you don't need to know all of them though, we teach each others). We build open source tools for Angular, Vue.js, React but also plain JavaScript ("Vanilla JS" 🍦). We do so because our users are constantly giving us feedback about their needs via GitHub, our discourse forum or our support system. We are at the frontline of the developer experience at Algolia, a great position to have a big impact for both developers and end-users. This is an opportunity for someone to help design and make an immense impact at a fast growing company. You should value and practice transparency, have the humility to accept your weaknesses and continuously strive to improve both personally and professionally. Do you like, or would you like to, craft code, tools and libraries for developers? Do you love to design a clean API solving real-world use cases? Then apply and let's chat about it. Coming right from an engineer in the team : “As a developer, I use a ton of different libraries to achieve my goals of building applications. Now I can go to the next level and learn how to build tools for developers to build their applications. It's a whole different challenge, I do it in the open source world and engage with my users.”.
  • Architecture, design and develop new versions of Vue InstantSearch, React InstantSearch, InstantSearch.js, Angular InstantSearch as well as JS API Client and so much more with the help of the team
  • Implement new features, solve issues and analyse user's feedback on our popular open-source projects
  • Coordinate with our product, design and marketing teams on the release of new projects and websites
  • Take ownership, research, explore and deliver novel experiences
  • Teach us what we don't know and how you want to improve the search and discovery experience
  • Participate (new features, bug fixes) to other popular open-source projects related to our project needs
  • Be a technical mentor and help the team grow
  • Help define engineering best practices and processes

  • In a typical morning I would open my GitHub notifications and seek for any important subject: a customer needing help with a bug, a colleague asking for a pull request review. Then I would go back at coding and tackling one of the team objectives we set early in the quarter. Right after lunch, once per week we have a team meeting to discuss challenges at stake and progress.
  • Good knowledge of JavaScript (ES5, ES6), TypeScript, the DOM, HTML, CSS
  • You have created at least one reusable module (private or public)
  • Experience with at least one of the following frameworks React, Angular, Vue.js or Ember.js
  • A passion for shipping quality code
  • You have an eye for great user experiences (UX)
  • Willingness to go beyond what you know today
  • You like to help, teach and mentor your colleagues
  • Ability to interact with contributors and customers
  • Excellent spoken and written English skills required
  • Overall we care about your current and future skillset. Not where you studied or who do you know. We care about what you like to do and about what you'd like to do in the future, at Algolia.
  • Experience at our current stage and beyond ($50-200M ARR range, high growth, lots of change and building internal infrastructure).
  • You have built search and discovery experiences
  • You have experience with npm, Yarn, webpack, Rollup, Lerna
  • You have some UI design skills
  • You are able to show empathy towards your colleagues
  • You are a manager of one
  • You are interested in native or mobile web platforms (react-native)
  • We are not specifically looking for very active GitHub profiles (that's only a plus), we are looking for developers that know a bit and wants to create tools for others developers
  • GRIT - Problem-solving and perseverance capability in an ever-changing and growing environment
  • TRUST - Willingness to trust our co-workers and to take ownership 
  • CANDOR - Ability to receive and give constructive feedback.
  • CARE - Genuine care about other team members, our clients and the decisions we make in the company.
  • HUMILITY- Aptitude for learning from others, putting ego aside.
  • Private Medical Insurance
  • Life and Disability Insurance 
  • Business Travel Insurance
  • Relocation support
  • Company Canteen (high standard)
  • Flexible work hours and flexible time off
  • Open to remote from France and the UK
  • Competitive pay and equity in a healthy startup
  • Your choice of computer, phone, you name it: everything you need to be efficient and at ease
  • Coaching and sponsorship to attend, participate and speak at leading industry conferences
  • Ongoing professional education opportunities through internal & external workshops, including language learning (English/French), coding & more. 
  • Unique referral rewards program: refer a candidate, and we’ll donate to your charity of choice
  • Fully stocked office and kitchens, team workouts, meals & happy hours
  • Solutions Engineer - DACH
    Dublin | Paris | London |
    If you don't know Algolia yet, we've built our very own search engine designed to power engaging experiences, which we expose as an API. You may have used us without knowing it - we're now serving over 60B queries/month worldwide and the likes of Twitch, Medium, Weight Watchers and Stripe leverage our technology to power their search. Algolia is an API - we're convinced that customer-facing engineers can and should be leading the charge of adoption as we scale the business globally. We need help with our next stage of growth. We are currently looking for engineers to join our revenue teams in EMEA.
  • Find new and creative ways to leverage our API by combining an eye for business needs with technical feasibility - The Solutions Engineer drives the technical win by demonstrating what is possible, and inspire business stakeholders and developers.
  • Partner closely with account executives to lead 5 and 6 figure annual contracts by understanding the needs, and mapping them to Algolia capabilities.
  • Connect with software engineers, architects, business users and C-level executives to establish technical credibility, project feasibility and prove business cases.
  • Work with our internal product and engineering teams to push our product to the limit and feedback on how it stands up in the field.
  • Work on the forefront of one of the fastest growing SaaS businesses on the planet - new revenue is the life and blood of any business and if you've ever thought about creating a startup or expanding your network, this is an excellent opportunity to grow and learn in a way that goes far beyond just coding.
  • Excellent spoken and written English and German skills required
  • Strong desire to help people solve problems and an attention to detail
  • Ability to work with cross-functional teams, clients, partners and market analysts
  • Scripting experience in Python, JavaScript, PHP or other relevant languages
  • Prior experience in technical selling
  • Worked as a freelance, and dealt with customer-facing
  • GRIT - Problem-solving and perseverance capability in an ever-changing and growing environment.
  • TRUST - Willingness to trust our co-workers and to take ownership.
  • CANDOR - Ability to receive and give constructive feedback.
  • CARE - Genuine care about other team members, our clients and the decisions we make in the company.
  • HUMILITY - Aptitude for learning from others, putting ego aside.
  • Pension
  • Private Medical Insurance
  • Group Income Protection
  • Group Death in Service
  • Business Travel Insurance
  • Competitive pay and equity
  • Coaching and sponsorship to participate and speak at leading industry conferences
  • Ongoing professional education opportunities through internal & external workshops, including public speaking, language learning (English/French)
  • Fun: we spend time together — team building, socializing and making tools that encourage getting to know teammates across offices and continents.
  • Charitable contribution matching 
  • Unique referral rewards program: refer a candidate, and we’ll donate to your charity of choice
  • Corporate flats available for the first months of relocation and when you travel to different offices
  • Fully stocked kitchens
  • Team workouts
  • Meals & happy hours
  • Verified by
    Marketing Specialist
    Engineering Lead
    Co-Founder & CEO
    Software Engineer
    Software Engineer
    Front-end developer
    Software engineer
    Frontend Engineer
    Frontend Developer
    Information Technology
    Content & Education
    VP of Engineering
    Software engineer
    Customer Solutions Engineer
    Software Engineer
    Senior JavaScript Engineer
    You may also like