How Algolia Reduces Latency For 21B Searches Per Month

19,290
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
Solutions Architect
San Francisco | New York
At Algolia, we are passionate about helping developers & product teams connect their users with what matters most in milliseconds! Algolia is leading the way in removing the frictional boundary between intent and content, providing industry grade search and discovery tools to drive richer, more powerful engagement and success capabilities to companies of all sizes. In this endeavor, we seek passionate and industrious Solutions Architects ready to join a hyper-growth business to drive technical success in product implementation and adoption. Solutions Architects sit within the Field Engineering Organization, chartered with driving technical success and adoption of our most strategic enterprise customers. The Algolia product is a powerful platform, but it is the implementation that propels the highest customer outcomes. Solutions Architects take responsibility in owning Algolia solution patterns and consultation as trusted advisors to the enterprise customer base. The Solutions Architect team is also a key driver in the creation and prioritization of the core product roadmap, enabling and ensuring our valued customers successfully leverage Algolia. Prototyping, developing and sharing unique tailored solutions via workshops and collateral - both internally and externally - helps both Algolia, and the depth of your own solution mastery. A key responsibility will be to lead, evaluate and contribute to our customer’s design efforts and advising customers on topics including vision, strategy and best practices for deployment of Algolia products, increasing adoption of Algoia products, and metrics for measuring the effectiveness of Algolia product deployments. An ideal background includes previous experience in a development and consulting role. The candidate is a seasoned professional with strong technical and business architecture experience to support the full Algolia product scope. Excellent relationship skills and the ability to partner across customer business units, other internal business units, and product teams will be critical to support delivery of expected outcomes.
  • Be a Trusted Advisor; engage with our customers’ technical architects and business stakeholders to provide high-quality technical solutions and product training to drive successful customer outcomes
  • Link business processes with product technical solutions
  • Execute delivery methodology to drive projects to completion on time and on budget
  • Troubleshoot key customer implementation issues and demonstrate ability to drive successful resolution
  • Prototype and catalog new solutions to fit business pain points
  • Consult on architecture, indexing, searching, and UI best practices
  • Expand relationship and product usage within the enterprise segment
  • Engage in customer calls and on-site visits to help inform and align on product roadmaps for future partnership growth
  • Aid in the development of detailed action plan, roadmap, prototype, final recommendation document, SM Action Plan and RetrospectivePartner with Success Management and Engagement Manager and other internal roles to understand project goals and deliverables
  • Create and increase reusability of solutions content (blog posts, workshop tutorials, etc), tooling, and internal projects
  • Build out tooling and/or collateral to help scale customer engagementInform and ultimately evolve product ecosystem by listening and advocating for customers technical needs
  • Work with Engineering to track and resolve feature requests and bugs
  • Meet with Product to stay informed on the latest changes to Algolia ecosystem and disseminate internally and to customers as appropriate
  • Polished consulting skills: keen awareness of sensitive client topics capability to tactfully navigate and effectively address client messaging and recommendations
  • 2+ years professional experience as a full-stack web developer:
  • Recommended proficiency in Javascript/HTML/CSS for the front-end
  • Recommended proficiency in a backend framework (i.e. node, Rails, Django, etc.)
  • Ability to establish credibility and rapport with Senior Executives and technical and non-technical team members
  • Excellent analytical and problem solving skills with a history of hands-on project management of large and small initiatives
  • Ability to prioritize tasks effectively with a high-level of attention to detail
  • Ability to quickly define dependencies, issues, and outline mitigation plans against risks
  • Ability to work under tight deadlines while being flexible and responding to changing business and technical conditions
  • Ability to communicate effectively to both the technology and business communities
  • Consistent history of business-building successes and passion for results 
  • Don’t think you fit 100% of the requirements? We’d still love to hear from you.
  • Backend/frontend mobile development
  • Analytics, A/B testing
  • Familiarity in relevant verticals
  • E-commerce/SaaS/MediaProject management experience
  • Experience within search domain and search-as-a-service companies
  • Elastic/Solr
  • 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.
  • Health, dental, and vision benefits for you and your family
  • Life insurance and disability benefits
  • Paid parental leave
  • 401(k) plan
  • Flexible work hours and unlimited time off
  • Competitive pay and equity
  • Your choice of computer, phone, keyboard, headphones, you name it. Everything you need to be efficient.
  • Coaching and sponsorship to participate and speak at leading industry conferences
  • 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
  • Senior Demo Engineer
    San Francisco
    We are looking for a tech-savvy, code-capable Senior Demo Engineer with excellent communication skills to join Algolia. You are someone that's excited to build state of the art demos and prototypes, gets excited about great front end UI design and new technologies, and knows how to translate technical product capabilities into business benefits. The role involves ownership and project management of technical marketing initiatives, such as those below, working closely with other members of marketing, product management, engineering, and solutions engineering. 
  • Build demo experiences and prototypes for multiple devices and industry use cases (eCommerce, Media, Site Search, and Voice), across web, app and mobile. Curate and evolve these assets for use in events, webinars, technical briefings, product launches, training videos and online content. Enrich demo data and flow for compelling storytelling, to showcase how Algolia drives tangible business outcomes. 
  • Develop subject matter expertise on front end UX design best practice for compelling, consumer grade search experiences, as well as back end indexing and search relevance optimization, incorporating personalization and A/B testing. Capture and curate technical best practice from existing customers to drive thought leadership. 
  • Develop technical content: Create content to educate developer prospects and customers about our solutions, as well as excite, motivate, and inspire them to use Algolia to build better search experiences. 
  • Product launches: Work with Product Management and Product Marketing to create easy to understand visualizations (screenshots, short demos, diagrams) of key functionalities to build effective business storytelling.

  • 5+ years of product marketing, sales engineering or technical evangelism experience in a software development, SaaS, managed service, or hosted API company, ideally in the platform and/or developer technology space.
  • Outstanding written communication skills: the ability to write knowledgeably, clearly and persuasively for a diverse range of audiences.
  • Strong affinity for developers as a target market, with a deep understanding of the landscape of tools and technologies developers use to bring products to market, including platform-as-a-service offerings.
  • Self-starter who truly enjoys working in a fast-paced, innovative software start-up environment.
  • Backend/frontend web development (Javascript, Java, Python, etc)
  • Comfortable with APIs.

  • 2+ years professional experience as a full-stack developer
  • Experience with search domain Elastic/Solr
  • Familiarity/curiosity with multiple technical domains
  • Analytics, A/B testing experience
  • Exposure to enterprise business
  • Mobile experience background
  • Familiarity in relevant verticals E-commerce/SaaS/Media
  • Experience at other search-as-a-service companies
  • Spoken at tech conferences

  • 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 

  • Technical Support Engineer - US (East...
    US | | East coast
    *Note: This is NOT a Desktop support/IT position. This role will be required to work Eastern time zone 8 AM - 5 PM ET* At Algolia, we are passionate about helping developers & product teams connect their users with what matters most in milliseconds! 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. The Technical Support Engineer is a critical role at Algolia.  This role is on the front-lines of our company and is often the first person customers contact when they are experiencing problems with our products or services. We're looking for a Technical Support Engineer to assist our technical customers with implementing and supporting Algolia in a variety of web and mobile development technical stacks. This could mean helping a developer trying to build the next big thing in their garage, or Fortune 500 companies (like Medium, Twitch from Amazon, LVMH, ...) focused on providing a world-class experience to their millions of users. As a Technical Support Engineer you will partner with the customer success, product and engineering teams. We have a hands-on culture, and expect you to roll up your sleeves and get to work solving difficult problems that stand in the way of our customers being successful.
  • Handle product and technical requests via phone, web, and email support channels.
  • Effectively troubleshoot and properly document customer’s support issues.
  • Provide customers with regular updates regarding their support tickets.
  • Conduct professional and empathetic conversations with customers to gather information, troubleshoot, and resolve their technical obstacles.
  • Submit software bug reports to the Engineering team for problems needing attention.
  • Partner with Product Teams and Engineering to develop subject matter expertise and serve as a product expert to the rest of the support team.
  • Contribute to internal and external knowledge bases
  • 3-6 years of experience in Technical Support, supporting SaaS enterprise software.
  • Working knowledge of development languages such as JavaScript, Java, PHP, C#, Objective-C, Swift, Ruby, Python.
  • Experience with REST API, database management, and web development technologies.
  • Strong desire to help people solve problems with the ability to explain complex technical  concepts to a broad audience
  • Ability to handle and prioritize a portfolio of tickets at various stages of resolution.
  • Effective communication skills across channels (phone, email, & chat), demonstrating compassion and empathy towards customers.
  • Algolia operates a 24/7 support center, ability to work weekends and holidays as needed may be required.
  • Basic familiarity with iOS & Android platforms.
  • Experience supporting open-source projects & their GitHub communities.
  • Working in a 24/7 contact center environment
  • Experience with Shopify, Magento, and Salesforce.com a plus
  • 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
  • Unlimited Paid Time Off 
  • Paid Parental Leave
  • Pre-tax commuter benefits 
  • Life insurance and disability benefits 
  • Competitive pay and equity
  • Charitable contribution matching 
  • Fully stocked kitchens
  • Catered lunches on Tuesdays and Thursdays 
  • Workout Wednesdays w/ personal trainer 
  • Bi-monthly meditation sessions 
  • Technical Support Engineer - US (APAC...
    US | | Pacific
    *Note: This is NOT a Desktop support/IT position. This role will be required to work APAC time zone 2 PM - 11 PM PT* At Algolia, we are passionate about helping developers & product teams connect their users with what matters most in milliseconds! 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. The Technical Support Engineer is a critical role at Algolia.  This role is on the front-lines of our company and is often the first person customers contact when they are experiencing problems with our products or services. We're looking for a Technical Support Engineer to assist our technical customers with implementing and supporting Algolia in a variety of web and mobile development technical stacks. This could mean helping a developer trying to build the next big thing in their garage, or Fortune 500 companies (like Medium, Twitch from Amazon, LVMH, ...) focused on providing a world-class experience to their millions of users. As a Technical Support Engineer you will partner with the customer success, product and engineering teams. We have a hands-on culture, and expect you to roll up your sleeves and get to work solving difficult problems that stand in the way of our customers being successful.
  • Handle product and technical requests via phone, web, and email support channels.
  • Effectively troubleshoot and properly document customer’s support issues.
  • Provide customers with regular updates regarding their support tickets.
  • Conduct professional and empathetic conversations with customers to gather information, troubleshoot, and resolve their technical obstacles.
  • Submit software bug reports to the Engineering team for problems needing attention.
  • Partner with Product Teams and Engineering to develop subject matter expertise and serve as a product expert to the rest of the support team.
  • Contribute to internal and external knowledge bases
  • 3-6 years of experience in Technical Support, supporting SaaS enterprise software.
  • Working knowledge of development languages such as JavaScript, Java, PHP, C#, Objective-C, Swift, Ruby, Python.
  • Experience with REST API, database management, and web development technologies.
  • Strong desire to help people solve problems with the ability to explain complex technical  concepts to a broad audience
  • Ability to handle and prioritize a portfolio of tickets at various stages of resolution.
  • Effective communication skills across channels (phone, email, & chat), demonstrating compassion and empathy towards customers.
  • Algolia operates a 24/7 support center, ability to work weekends and holidays as needed may be required.
  • Basic familiarity with iOS & Android platforms.
  • Experience supporting open-source projects & their GitHub communities.
  • Working in a 24/7 contact center environment
  • Experience with Shopify, Magento, and Salesforce.com a plus
  • 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
  • Unlimited Paid Time Off 
  • Paid Parental Leave
  • Pre-tax commuter benefits 
  • Life insurance and disability benefits 
  • Competitive pay and equity
  • Charitable contribution matching 
  • Company Provided Equipment
  • 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