Scale your Laravel application with Neon Postgres Read Replicas
Learn how to scale Laravel applications with Neon Postgres Read Replicas
Introduction
Neon read replicas are independent read-only compute instances that can significantly enhance database performance and scalability. By distributing read operations across these replicas, you can reduce latency and improve overall system responsiveness, especially for read-heavy applications.
A key advantage of Neon's architecture is that adding a read replica doesn't require additional storage, making it a highly efficient scaling solution. This cost-effective approach is ideal for businesses of all sizes that need to improve database performance without increasing storage costs.
This guide demonstrates how to leverage Neon read replicas to efficiently scale Laravel applications. You'll learn how to configure your Laravel database connections to work with read replicas, enabling you to optimize your database operations and improve overall application performance. We'll use a simple URL shortener application as an example.
Prerequisites
- A Neon account and a Project. If you don't have one, you can sign up for a Neon account and create a project by following the Getting Started guide.
- Basic knowledge of Laravel and PHP
- Composer installed on your local machine
- PHP installed on your local machine
Build the URL Shortener app
To demonstrate how to use Neon read replicas with Laravel, we'll build a simple URL shortener application that uses a Neon database. We'll then update the application to use a read replica for read operations, improving the application's performance and scalability.
Part 1: Build the initial URL Shortener app with a single database
Set up the project
Create a new Laravel project:
Configure the database connection
Update your .env
file with your Neon database credentials:
Create the database schema
Create a new migration for the urls
table:
Edit the migration file in database/migrations
:
Run the migration:
important
Neon supports both direct and pooled database connection strings, which can be copied from the Connection Details widget on your Neon Project Dashboard. A pooled connection string connects your application to the database via a PgBouncer connection pool, allowing for a higher number of concurrent connections. However, using a pooled connection string for migrations can be prone to errors. For this reason, we recommend using a direct (non-pooled) connection when performing migrations. For more information about direct and pooled connections, see Connection pooling.
Create the model
Create a new model for the URL:
Edit app/Models/Url.php
:
Create the controller
Create a new controller for handling URL operations:
Edit app/Http/Controllers/UrlController.php
:
Set up the routes
Edit routes/web.php
:
Create a simple frontend
Create a new blade template resources/views/home.blade.php
:
Run the application
Start the Laravel development server:
Visit http://localhost:8000
to test the URL shortener app.
Part 2: Use a read replica for read-only operations
Create a read replica on Neon
To create a read replica:
- In the Neon Console, select Branches.
- Select the branch where your database resides.
- Click Add Read Replica.
- On the Add new compute dialog, select Read replica as the Compute type.
- Specify the Compute size settings options. You can configure a Fixed Size compute with a specific amount of vCPU and RAM (the default) or enable autoscaling by configuring a minimum and maximum compute size. You can also configure the Suspend compute after inactivity setting, which is the amount of idle time after which your read replica compute is automatically suspended. The default setting is 5 minutes.
note
The compute size configuration determines the processing power of your database. More vCPU and memory means more processing power but also higher compute costs. For information about compute costs, see Billing metrics.
- When you finish making selections, click Create.
Your read replica compute is provisioned and appears on the Computes tab of the Branches page.
Navigate to the Dashboard page, select the branch where the read replica compute was provisioned, and set the compute option to Replica to obtain the read replica connection string:
Update the database configuration
Edit config/database.php
to add the read replica configuration:
info
Now that you've completed the database migrations, you can leverage the pooled connection string for both read and write operations. This streamlines your database interactions. However, it's worth noting that for future migrations, it's best practice to use the direct connection string. This approach helps avoid potential complications that might arise during the migration process.
Update your .env
file with the read replica host:
Automatic Query Routing with Eloquent
One of the great features of Laravel's Eloquent ORM is that it automatically routes queries to the appropriate database connection based on the type of query. This means that after configuring your read replica, you don't need to make any changes to your existing controller or model code. Here's how Eloquent handles different types of queries:
- Read Operations:
SELECT
queries are automatically routed to the read replica. - Write Operations:
INSERT
,UPDATE
, andDELETE
queries are sent to the primary (write) database.
This automatic routing happens transparently, allowing you to scale your application without modifying your application logic.
tip
Laravel offers powerful flexibility in managing database connections. While automatic query routing is convenient, you can easily override it when needed. For instance, to explicitly use the write connection for querying the urls table, you can do the following:
You can find the source code for the application described in this guide on GitHub.
Conclusion
By leveraging Neon's read replicas with Laravel, you can significantly improve your application's performance and scalability. Laravel's database configuration makes it easy to set up and use read replicas without having to manually manage multiple database connections in your application code.
This setup allows you to distribute your read load across one or more read replicas while ensuring that all write operations are performed on the primary database. Monitor your application's performance and adjust the number of read replicas as needed to handle your specific load requirements.
By implementing read replicas in your Laravel application, you're taking a significant step toward building a more scalable and performant system that can handle increased traffic and data loads.
Need help?
Join our Discord Server to ask questions or see what others are doing with Neon. Users on paid plans can open a support ticket from the console. For more details, see Getting Support.