Scaling PostgreSQL at Thumbtack: Load Balancing And Health Checks

6,241

By Marco Almeida, Site Reliability Engineer at Thumbtack.


Introduction

Running PostgreSQL on a single primary master node is simple and convenient. There is a single source of truth, one instance to handle all reads and writes, one target for all clients to connect to, and only a single configuration file to maintain. However, such a setup usually does not last forever. As traffic increases, so does the number of concurrent reads and writes, the read/write ratio may become too high, a fast and reliable recovery plan needs to exist, the list goes on…

No single approach solves all possible scaling challenges, but there are quite a few options for scaling PostgreSQL depending on the requirements. When the read/write ratio is high enough, there is fairly straightforward scaling strategy: setup secondary PostgreSQL nodes (replicas) that stream data from the primary node (master) and split SQL traffic by sending all writes (INSERT, DELETE, UPDATE, UPSERT) to the single master node and all reads (SELECT) to the replicas. There can be many replicas, so this strategy scales better with a higher read/write ratio. Replicas are also valuable to implement a disaster recovery plan as it’s possible to promote one to master in the event of a failure.

Context

In 2014, Thumbtack was running PostgreSQL 9.1 on two servers: a basic master – slave setup leveraging PostgreSQL’s built-in streaming replication. Our infrastructure was comprised of a few dozen physical machines on SoftLayer running RHEL 5 and we were using HAproxy with Keepalived for load balancing. The future, already being planned for, would be powered by EC2 instances on AWS, running Debian 7 behind Elastic Load Balancers.

As traffic grew, we knew we would need to scale out PostgreSQL further. Thumbtack’s SQL traffic was (and still is) quite read-intensive, with less than 3% of all queries being executed on the master node. This was good news as it meant we could scale out by sending SELECT statements to a cluster of read-only replicas and leaving the master alone to process DML commands.

In order to properly implement this we would need:

  • an arbitrary number of read-only replicas behind a load balancer;
  • the load balancer itself could not be a single point of failure;
  • a way of performing health checks on each server, executed from the load balancer, so that failed nodes would be taken in and out of rotation automatically;
  • to support SoftLayer and AWS environments during the transition period.

Replication, high-availability, and load-balancing

We knew what we wanted the infrastructure to look like from a high-level perspective and had the tools available to implement almost all of it on both providers (Fig. 1).

Thumbtack Postgres Acrhictecture

One critical detail, however, was far from being a solved problem: health checks.

A basic ping on port 5432 was not enough. Performance and replication lag were (and still are!) very important factors to us — if a given replica is lagging behind by more than N (varying according to the database and the cluster we’re connecting to) seconds, we prefer not to use it until it recovers as it would otherwise lead to stale reads.

Custom health checks

Not having found an open source tool that implements powerful enough health-checks for PostgreSQL, we decided to write our own. These were the requirements:

  1. Work equally well on both environments — RHEL 5/HAproxy on Softlayer and Debian 7/ELBs on AWS
  2. Check basic TCP connectivity, on an arbitrary port, with a configurable timeout
  3. Check server availability by running a test query with a time limit — if a server is under load, it may be responding to TCP but not able to process a simple query (SELECT 1). We need to distinguish between these two scenarios, and potentially take different actions
  4. Check replication lag (time elapsed since the last transaction was replayed)
  5. Support custom health checks in the form of SQL queries — extensible and future-proof
  6. Low memory footprint — avoid “stealing” memory from PostgreSQL
  7. Minimal list of external dependencies

A web service, exposing a simple HTTP endpoint, would work in any environment and easily be able to test TCP connectivity. Simple queries and testing replication lag are just a special case of running arbitrary SQL queries as a health check, so we just focused on this one and implemented the others as a form of syntactic sugar.

Programming languages One important decision for delivering a platform independent solution with low memory footprint and minimal dependencies was the choice of the programming language. We considered a few from Python (there was already a reasonably large Python code base at Thumbtack), to Go (we were taking our first steps with it), and even Rust (too immature at the time).

We ended up writing it in C. It was easy to meet all requirements with only one external dependency for implementing the web server, clearly no challenges running it on any of the Linux distributions we were maintaining, and arguably the implementation with the smallest memory footprint given the choices above.

The final result

We named the project pgDoctor and made it publicly available on our Github repository. It uses microhttpd to implement a very simple web service that listens on port 8071, logs to the local7 syslog facility (configurable), and provides a reasonably rich set of configuration parameters. The behavior is quite simple: an HTTP GET request to :8071 returns 200 if all checks pass, 500 otherwise. All errors are logged.

pgDoctor has been running flawlessly on all our PostgreSQL replicas for roughly 3 years now, having gone through two major upgrades (9.1 –> 9.4 –> 9.6). As of now, there are 18 streaming replicas, all running pgDoctor alongside PostgreSQL, and distributed among 4 clusters. Each cluster supports different use cases and requires slightly different health checks.

PostgreSQL replicas are sometimes taken out of rotation. The most common reasons are temporary high replication lag or some transient issue with the underlying EC2 instance. As expected, they are added back to the cluster without any intervention once normality is restored and the health checks succeed.

Figure 2 shows a diagram of (a downsized version of) our production environment:

  • Three availability zones;
  • One master node and two hot-standby instances on different availability zones;
  • Three clusters of read-only replicas, streaming from the master, each with its own load balancer;
  • Several clients, on all availability zones, reading from one or more clusters and writing to the master.

Thumbtack Postgres Architecture 2

Does this sound interesting? There is a lot more to be done. Join Thumbtack and help us build, scale, and operate a high reliability service!

Related work

http://www.severalnines.com/mysql-load-balancing-haproxy-tutorial#issues https://www.digitalocean.com/community/tutorials/how-to-use-haproxy-to-set-up-mysql-load-balancing--3 http://www.severalnines.com/mysql-load-balancing-haproxy-tutorial#issues


Originally posted on Thumbtack Engineering

Tools mentioned in article
Open jobs at Thumbtack
iOS Engineer
San Francisco

Have you ever tried to hire a plumber? How about a house cleaner? If you have, chances are it took you way longer than it should. In the era of instant-everything, it’s crazy that you still have to waste an entire afternoon researching, calling and vetting local service professionals whenever you need one. The market for hiring them is huge — $1 trillion in the US alone — but the process is inefficient and largely offline.

Thumbtack is transforming this experience end-to-end, building a marketplace that matches millions of people with local pros for almost any project. In making these connections, not only do our customers get more done every day, our pros are able to grow their businesses and make a living doing what they’re great at.

These customers and pros come from all walks of life and every zip code in the country. We want our team to reflect that. If you come from an underrepresented background in tech, we strongly encourage you to apply. We challenge ourselves every day to make this a place where you can thrive just the way you are, so we can build a product that does the same for our customers and pros.

About the Engineering Team

At Thumbtack, engineers at every level build products and systems that directly impact our customers and professionals. Our challenges span a wide variety of areas, ranging from building search and booking experiences, to optimizing pricing systems, to building tools to help professionals grow their businesses. We believe in tackling these hard problems together as a team, with strong values around collaboration, ownership and transparency. To read more about the hard problems that our team is taking on, visit our engineering blog.

About the Role

We are looking to build an amazing mobile experience for hundreds of thousands of users. Can you imagine what you might do if you could run your business from your phone? If you could hire a service provider at any time day or night with just a few taps? The sky's the limit. We develop much of our products mobile first and have seen this investment pay off incredibly. We’re looking for engineers excited to build a fantastic product.

Responsibilities

  • Drive engineering projects to completion, with a tenacious focus on the business impact of those projects. Skilled at prioritizing tasks to deliver on goals with a sense of urgency.
  • Execute new ideas quickly and effectively on iOS while also being a resource to other teams and engineers.
  • Willing, when necessary, to solve tough technical problems at any level of the stack, and be persistent in getting to the solution.
  • Work collaboratively with cross-functional teams to plan and execute on engineering projects.

Must-Have Qualifications

If you don't think you meet all of the criteria below but still are interested in the job, please apply. Nobody checks every box, and we're looking for someone excited to join the team.

  • Passionate iOS engineer who is an expert in  building, testing, releasing, and maintaining applications in either Swift or Objective C
  • Minimum of 4 years of industry experience in engineering
  • History of shipping consumer focused apps that users love on the App Store, you can show what you’ve owned
  • Excited by the potential of mobile technology to transform the lives of small businesses around the country

Nice-to-Have Qualifications

  • Experience with popular libraries, frameworks, and services like Core Data, AFNetworking, Xcode UI Testing, Crashlytics, and Amplitude, including when not to use one
  • Strong eye for beautiful design and user experience
  • Great communicator; we find that people who are good writers tend to be great thinkers and great coders
  • You’re data-­driven and dedicated to thorough testing to maintain high-­quality software

More About Us

Thumbtack is a local services marketplace that connects customers who need to get things done with local, skilled professionals who can help. From plumbers and painters to DJs and personal trainers, Thumbtack helps millions of customers find the right professional for their project in 1,000 unique categories. Founded in 2009 and headquartered in San Francisco, Thumbtack is backed by over $250 million in investment from Sequoia Capital, CapitalG, Tiger Global Management, Javelin Investment Partners and Baillie Gifford.

Thumbtack embraces diversity. We are proud to be an equal opportunity workplace and do not discriminate on the basis of sex, race, color, age, sexual orientation, gender identity, religion, national origin, citizenship, marital status, veteran status, or disability status. Pursuant to the San Francisco Fair Chance Ordinance, we will consider for employment qualified applicants with arrest and conviction records.

The California Consumer Privacy Policy Act (the "CCPA") obligates covered businesses to disclose to consumers (including employees and job applicants), at or before the point of collecting personally identifiable information ("PII"), the categories of PI to be collected and the purposes for which the categories of PI shall be used. 

In the course of the job application process, we may collect the following categories of PI for the purposes of evaluating you as a job applicant: 

  • Identifiers such as a real name, alias, postal address, unique personal identifier, online identifier, Internet Protocol address, email address, account name, driver’s license number, passport number, social security number, or other similar identifiers;
  • Professional or employment-related information. 

We will not collect any additional categories of personal information or use your personal information collected for any other purpose without providing you with additional notice consistent with the CCPA.

 

#LI-EZ1

Site Reliability Engineer
San Francisco

Have you ever tried to hire a plumber? How about a house cleaner? If you have, chances are it took you way longer than it should. In the era of instant-everything, it’s crazy that you still have to waste an entire afternoon researching, calling and vetting local service professionals whenever you need one. The market for hiring them is huge — $1 trillion in the US alone — but the process is inefficient and largely offline.

Thumbtack is transforming this experience end-to-end, building a marketplace that matches millions of people with local pros for almost any project. In making these connections, not only do our customers get more done every day, our pros are able to grow their businesses and make a living doing what they’re great at.

These customers and pros come from all walks of life and every zip code in the country. We want our team to reflect that. If you come from an underrepresented background in tech, we strongly encourage you to apply. We challenge ourselves every day to make this a place where you can thrive just the way you are, so we can build a product that does the same for our customers and pros.

About the Engineering Team

At Thumbtack, engineers at every level build products and systems that directly impact our customers and professionals. Our challenges span a wide variety of areas, ranging from building search and booking experiences, to optimizing pricing systems, to building tools to help professionals grow their businesses. We believe in tackling these hard problems together as a team, with strong values around collaboration, ownership and transparency. To read more about the hard problems that our team is taking on, visit our engineering blog.

About the Role

Our Site Reliability Engineers are a hybrid of software and systems engineers. Our current mission is to design Thumbtack’s next version of the core infrastructure. We code our way out of operational problems. We are responsible for reliability, scalability, and automation while keeping an eye on latency, performance, and capacity.

Responsibilities

  • Design, write, and maintain software to improve the availability, scalability, latency, and efficiency of Thumbtack's services, incorporating third-­party open-source tools when available.
  • Create new designs for a growing number of distributed systems.
  • Design and implement the tools and processes used for deployment and change management.
  • Plan and execute configuration management.
  • Own, maintain, and continuously improve all systems provided as a service, such as monitoring and datastores.
  • Engage in service capacity planning and demand forecasting, anticipating performance bottlenecks.
  • Automate resource provisioning and allocation process.
  • Run software performance analysis and system tuning
  • Plan and execute disaster recovery drills
  • Participate in rotating on-call duties

Must-Have Qualifications

If you don't think you meet all of the criteria below but still are interested in the job, please apply. Nobody checks every box, and we're looking for someone excited to join the team.

  • Fluent in one or more of: C, Python, Go
  • Minimum of 4 years of industry experience in engineering
  • Familiarity with algorithms, data structures, and complexity analysis
  • In-depth knowledge of operating systems (processes, threads, IPC, concurrency, locks, mutexes, semaphores, etc.)
  • Experience working with Unix/Linux systems from kernel to shell and beyond, with experience working with system libraries, file systems, and client-server protocols
  • Experience with network protocols and theory (TCP/IP, UDP, ICMP, MAC addresses, IP packets, DNS, OSI layers, and load balancing, etc.)
  • Experience with Puppet, or some other configuration management tool
  • Systematic problem solving approach
  • Strong sense of ownership and drive

Nice-to-Have Qualifications

  • Expertise in designing, analyzing, and troubleshooting large-scale distributed systems
  • Experience with Amazon Web Services
  • Experience with PostgreSQL tuning and performance

More About Us

Thumbtack is a local services marketplace – one of the largest in the U.S. – that helps millions of people hire local professionals. With hundreds of unique service categories, customers can find a Thumbtack pro for almost anything: landscapers, DJs, personal trainers, even piano teachers. And in making these connections, we empower local pros too. Helping them get new customers and make a living doing what they’re great at.

Founded in 2008 and headquartered in San Francisco, Thumbtack is backed by over $250 million in investment from Sequoia Capital, CapitalG, Tiger Global Management, Javelin Investment Partners and Baillie Gifford.

Thumbtack embraces diversity. We are proud to be an equal opportunity workplace and do not discriminate on the basis of sex, race, color, age, sexual orientation, gender identity, religion, national origin, citizenship, marital status, veteran status, or disability status. Pursuant to the San Francisco Fair Chance Ordinance, we will consider for employment qualified applicants with arrest and conviction records.

The California Consumer Privacy Policy Act (the "CCPA") obligates covered businesses to disclose to consumers (including employees and job applicants), at or before the point of collecting personally identifiable information ("PII"), the categories of PI to be collected and the purposes for which the categories of PI shall be used. 

In the course of the job application process, we may collect the following categories of PI for the purposes of evaluating you as a job applicant: 

  • Identifiers such as a real name, alias, postal address, unique personal identifier, online identifier, Internet Protocol address, email address, account name, driver’s license number, passport number, social security number, or other similar identifiers;
  • Professional or employment-related information. 

We will not collect any additional categories of personal information or use your personal information collected for any other purpose without providing you with additional notice consistent with the CCPA.

#LI-LP1

Senior Data Engineer
San Francisco

Have you ever tried to hire a plumber? How about a house cleaner? If you have, chances are it took you way longer than it should. In the era of instant-everything, it’s crazy that you still have to waste an entire afternoon researching, calling and vetting local service professionals whenever you need one. The market for hiring them is huge — $1 trillion in the US alone — but the process is inefficient and largely offline.

Thumbtack is transforming this experience end-to-end, building a marketplace that matches millions of people with local pros for almost any project. In making these connections, not only do our customers get more done every day, our pros are able to grow their businesses and make a living doing what they’re great at.

These customers and pros come from all walks of life and every zip code in the country. We want our team to reflect that. If you come from an underrepresented background in tech, we strongly encourage you to apply. We challenge ourselves every day to make this a place where you can thrive just the way you are, so we can build a product that does the same for our customers and pros.

About the Engineering Team

At Thumbtack, engineers at every level build products and systems that directly impact our customers and professionals. Our challenges span a wide variety of areas, ranging from building search and booking experiences, to optimizing pricing systems, to building tools to help professionals grow their businesses. We believe in tackling these hard problems together as a team, with strong values around collaboration, ownership and transparency. To read more about the hard problems that our team is taking on, visit our engineering blog.

About the Role

As our first Senior Data Engineer, you will help build a new Data Engineering function focused on business intelligence, and play a leading role on our new Analytics Infrastructure team. You’ll be expected to develop a foundational, strategic vision for how we can continue to scale our world-class data environment and make our data accessible and digestible for reporting and analysis across the company. You’ll collaborate with our Analytics, Infrastructure, and Data Services teams to manage and own our data warehouse used by hundreds across the company to drive reporting and analysis. Over time you will implement a portfolio of tools that empower analysts across the company to analyze and enrich our terabytes of data about our customers and pros. We’re looking for a skilled data engineer and leader who can blend deep technical understanding with a bias for action and a strong sense of collaboration.

Responsibilities

  • Proactively drive the vision for BI and Data Warehousing across the company, and define and execute on a roadmap to achieve that vision
  • Design, architect, and maintain a data warehouse that supports a rapidly evolving product, in partnership with our stellar analytics and data services teams
  • Define, document and socialize foundational aspects of our reporting and analytical data model
  • Build and own the reporting pipelines and infrastructure that organize and structure our terabytes of data into digestible tables that empower analysis and reporting across the company
  • Drive data quality across key product and business areas
  • Collaborate closely with analysts to ensure our analytical infrastructure helps meet our company goals and allows product development to move fast
  • Partner with data services and product engineering teams to ensure consistent, seamless tracking and measurement of key company and product metrics

Must-Have Qualifications

If you don't think you meet all of the criteria below but still are interested in the job, please apply. Nobody checks every box, and we're looking for someone excited to join the team.

  • 5+ years experience working in business intelligence, data engineering, or a similar engineering role owning an RDBMS environment that serves analysis and reporting
  • Experience building data pipelines in a programming language like Python or Scala
  • Experience designing, architecting, and maintaining a data warehouse that seamlessly stitches together data from production databases, clickstream event data, and external APIs to serve teams of analysts
  • Capable project manager, can juggle a set of diverse projects with a strong track record of delivering against aggressive timelines
  • Excellent ability to understand the needs of and collaborate with stakeholders in other functions, especially the Analytics team

Nice-to-Have Qualifications

  • Experience managing a data engineering team
  • Experience in an online marketplace or similar consumer technology company
  • Experience with a modern public cloud based tech stack on AWS/GCP and the Google BigQuery data environment
  • Experience orchestrating data pipelines that serve hourly or daily metric reporting in Airflow
  • Experience with streaming or near-real time data pipelines
  • Experience building data pipelines in Scala

More About Us

Thumbtack is a local services marketplace – one of the largest in the U.S. – that helps millions of people hire local professionals. With hundreds of unique service categories, customers can find a Thumbtack pro for almost anything: landscapers, DJs, personal trainers, even piano teachers. And in making these connections, we empower local pros too. Helping them get new customers and make a living doing what they’re great at.

Founded in 2008 and headquartered in San Francisco, Thumbtack is backed by over $250 million in investment from Sequoia Capital, CapitalG, Tiger Global Management, Javelin Investment Partners and Baillie Gifford.

Thumbtack embraces diversity. We are proud to be an equal opportunity workplace and do not discriminate on the basis of sex, race, color, age, sexual orientation, gender identity, religion, national origin, citizenship, marital status, veteran status, or disability status. Pursuant to the San Francisco Fair Chance Ordinance, we will consider for employment qualified applicants with arrest and conviction records.

The California Consumer Privacy Policy Act (the "CCPA") obligates covered businesses to disclose to consumers (including employees and job applicants), at or before the point of collecting personally identifiable information ("PII"), the categories of PI to be collected and the purposes for which the categories of PI shall be used. 

In the course of the job application process, we may collect the following categories of PI for the purposes of evaluating you as a job applicant: 

  • Identifiers such as a real name, alias, postal address, unique personal identifier, online identifier, Internet Protocol address, email address, account name, driver’s license number, passport number, social security number, or other similar identifiers;
  • Professional or employment-related information. 

We will not collect any additional categories of personal information or use your personal information collected for any other purpose without providing you with additional notice consistent with the CCPA.

#LI-RA1 

Senior Android Engineer
San Francisco

Have you ever tried to hire a plumber? How about a house cleaner? If you have, chances are it took you way longer than it should. In the era of instant-everything, it’s crazy that you still have to waste an entire afternoon researching, calling and vetting local service professionals whenever you need one. The market for hiring them is huge — $1 trillion in the US alone — but the process is inefficient and largely offline.

Thumbtack is transforming this experience end-to-end, building a marketplace that matches millions of people with local pros for almost any project. In making these connections, not only do our customers get more done every day, our pros are able to grow their businesses and make a living doing what they’re great at.

These customers and pros come from all walks of life and every zip code in the country. We want our team to reflect that. If you come from an underrepresented background in tech, we strongly encourage you to apply. We challenge ourselves every day to make this a place where you can thrive just the way you are, so we can build a product that does the same for our customers and pros.

About the Engineering Team

At Thumbtack, engineers at every level build products and systems that directly impact our customers and professionals. Our challenges span a wide variety of areas, ranging from building search and booking experiences, to optimizing pricing systems, to building tools to help professionals grow their businesses. We believe in tackling these hard problems together as a team, with strong values around collaboration, ownership and transparency. To read more about the hard problems that our team is taking on, visit our engineering blog.

About the Role

We are looking to build an amazing mobile experience for hundreds of thousands of users. Can you imagine what you might do if you could run your business from your phone? If you could hire a service provider at any time day or night with just a few taps? The sky's the limit. We develop much of our products mobile first and have seen this investment pay off incredibly. We’re looking for engineers excited to build a fantastic product.

Responsibilities

  • Drive engineering projects to completion, with a tenacious focus on the business impact of those projects. Skilled at prioritizing tasks to deliver on goals with a sense of urgency.
  • Execute new ideas quickly and effectively in Android while also being a resource to other teams and engineers.
  • Willing, when necessary, to solve tough technical problems at any level of the stack, and be persistent in getting to the solution.
  • Work collaboratively with cross-functional teams such as Product and Design to plan and execute on engineering projects
  • Work on large projects and lead small teams of engineers

Must-Have Qualifications

If you don't think you meet all of the criteria below but still are interested in the job, please apply. Nobody checks every box, and we're looking for someone excited to join the team.

  • Minimum of 5 years of industry experience in engineering
  • Passionate Android engineer who is an expert in building, testing, releasing, and maintaining Android applications
  • History of shipping consumer focused apps that users love on the Play Store, you can show what you’ve owned
  • Excited by the potential of mobile technology to transform the lives of small businesses around the country

Nice-to-Have Qualifications

  • Experience with popular 3rd party libraries, frameworks, and services like RxJava, ButterKnife, AutoValue, Retrofit, Dagger, Crashlytics, and Amplitude, including when not to use one
  • Hands-on experience with Kotlin is a plus!
  • Strong eye for beautiful design and user experience
  • Familiarity with Material design principles and components
  • Great communicator; we find that people who are good writers tend to be great thinkers and great coders
  • You’re data-­driven and dedicated to thorough testing to maintain high-­quality software.

More About Us

Thumbtack is a local services marketplace that connects customers who need to get things done with local, skilled professionals who can help. From plumbers and painters to DJs and personal trainers, Thumbtack helps millions of customers find the right professional for their project in over 1,000 categories. Founded in 2009 and headquartered in San Francisco, Thumbtack is backed by over $420 million in investment from Sequoia Capital, CapitalG, Tiger Global Management, Javelin Investment Partners and Baillie Gifford. 

Thumbtack embraces diversity. We are proud to be an equal opportunity workplace and do not discriminate on the basis of sex, race, color, age, sexual orientation, gender identity, religion, national origin, citizenship, marital status, veteran status, or disability status. Pursuant to the San Francisco Fair Chance Ordinance, we will consider for employment qualified applicants with arrest and conviction records.

The California Consumer Privacy Policy Act (the "CCPA") obligates covered businesses to disclose to consumers (including employees and job applicants), at or before the point of collecting personally identifiable information ("PII"), the categories of PI to be collected and the purposes for which the categories of PI shall be used. 

In the course of the job application process, we may collect the following categories of PI for the purposes of evaluating you as a job applicant: 

  • Identifiers such as a real name, alias, postal address, unique personal identifier, online identifier, Internet Protocol address, email address, account name, driver’s license number, passport number, social security number, or other similar identifiers;
  • Professional or employment-related information. 

We will not collect any additional categories of personal information or use your personal information collected for any other purpose without providing you with additional notice consistent with the CCPA.

Verified by
You may also like