Serverless computing makes it easier for developers to build and run apps without worrying about managing and scaling servers. By combining Azure Functions with Neon's serverless Postgres, you can create scalable and cost-effective applications that handle high volumes of traffic with ease.
In this guide, we'll explore how to create a serverless referral system using Azure Serverless Functions and Neon Postgres. We'll build a simple serverless referral system that allows users to create referral codes, track successful referrals, and award points to referrers.
Prerequisites
Before we begin, make sure you have:
- Node.js 18.x or later installed
- Visual Studio Code with the Azure Functions extension
- An Azure account with an active subscription
- A Neon account and project
- Azure Functions Core Tools version 4.x
Creating Your Neon Project
Neon is now available in Azure! You can create serverless Postgres databases that run on Azure infrastructure. To learn more about Neon's Azure launch, check out the announcement post.
To create your Neon project on Azure:
- Navigate to the Neon Console
- Click Create Project
- Give your project a name
- Under Cloud Service Provider, select Azure
- Currently, Neon is available in the East US 2 region on Azure but more regions will be added soon
- Select the Compute size for your Neon database
- Click Create Project
Once created, save your connection details - you'll need these to configure your Azure Functions connection to Neon Postgres.
Database Schema Design
Let's start by designing the database schema for our referral system. We'll need tables to track users, referral codes, and rewards.
-
Create the
users
table: -
Create the
referral_codes
table: -
Create the
referrals
table to track successful user referrals:
With the three tables in place, our database schema:
- Tracks users and their total points
- Manages referral codes with usage limits and expiration dates
- Records each referral transaction
- Enforces data integrity through constraints
- Prevents duplicate referrals for the same user
Setting Up Your Development Environment
To start building serverless applications with Azure Functions you need to set up your development environment first.
Installing Required Tools
If you don't have the required tools installed, you can follow these steps to set up your development environment:
-
Install the Azure Functions extension for VS Code (if you haven't already):
- Open VS Code
- Click the Extensions icon or press
Ctrl+Shift+X
orCmd+Shift+X
- Search for "Azure Functions"
- Install the extension from Microsoft
-
Install Azure Functions Core Tools version 4.x:
In Visual Studio Code, select
F1
to open the command palette, and then search for and run the command 'Azure Functions: Install or Update Core Tools'.The Core Tools provide a local development environment and CLI commands for creating, testing, and deploying Azure Functions.
Project Setup
With the required Azure tools installed, you're ready to create your first Azure Functions project.
-
Open a terminal and navigate to the directory where you want to create your project.
Create a new directory for your project:
Change to the project directory:
Initialize a new Azure Functions project:
When prompted, select:
- Node.js as the runtime
- JavaScript as the language
This might take a few moments to complete, and it creates a basic project structure with the following files:
host.json
: Contains global configuration optionslocal.settings.json
: Stores app settings and connection strings for local developmentpackage.json
: Manages project dependencies
-
Install the required dependencies:
We're using:
pg
for Postgres connection to Neonuuid
for generating unique referral codesdotenv
for environment variables management
-
Configure your database connection by creating a
.env
file:Replace
user
,password
,ep-xyz.region
, andneondb
with your Neon connection details. -
Create a database utility file
src/utils/db.js
for our connection management:We will use this utility to execute queries against the Neon Postgres database across our Azure Functions.
With your project set up, you're ready to start building the core functions for your referral system.
Creating the Core Functions
We'll create several Azure Functions to handle different aspects of the referral system.
Each function will be an HTTP-triggered function that interacts with the Neon Postgres database to generate referral codes, process referrals, and retrieve referral statistics.
Other types of triggers, such as queue or timer triggers, can also be used depending on your requirements, but for this guide, we'll focus on HTTP triggers.
1. Generate Referral Code
Let's start by creating a function to generate unique referral codes for users.
Run the following command to create a new HTTP-triggered function:
This will create a new function in src/functions/generateReferralCode.js
. Open the file and replace the contents with the following code:
This function:
- Generates an 8-character referral code using
uuidv4
- Inserts the code into the
referral_codes
table with a 30-day expiration - Returns the generated code and expiration date
The endpoint will be available at http://localhost:7071/api/generateReferralCode
and expects a JSON payload with the userId
of the referrer. We'll be testing this function shortly once all functions are in place.
2. Process Referral
With the referral code generation function in place, let's create a function to process referrals when new users sign up.
Create a new HTTP-triggered function, again using the Azure Functions CLI:
This will create a new function in src/functions/processReferral.js
. Replace the contents with the following code:
There is a bit more going on in this function, so let's break it down:
- The function accepts
POST
requests with the referral code, new user email, and name - It starts a transaction to ensure data integrity
- Verifies the referral code is valid and not expired
- Creates a new user record
- Records the referral transaction
- Updates the referral code usage and awards points to the referrer
- Commits the transaction if successful, otherwise rolls back
The endpoint will be available at http://localhost:7071/api/processReferral
and expects a JSON payload with the referral code, new user email, and name.
3. Get Referral Stats
Finally, let's create a function to retrieve referral statistics for a given user.
Create a new HTTP-triggered function using the Azure Functions CLI:
Open the generated file src/functions/getReferralStats.js
and replace the contents with the following code:
Let's again break down the function:
- The function accepts
GET
requests with auserId
query parameter - It retrieves the total points, total referrals, successful referrals, and recent referrals for the given user
- The query joins the
users
andreferrals
tables to calculate the statistics - The results are returned as JSON
The endpoint will be available at http://localhost:7071/api/getReferralStats?userId=1
, where userId
is the ID of the user to fetch statistics for.
Testing Your Functions Locally
With all the core functions in place, it's time to test them locally before deploying to Azure.
Let's test each function locally to ensure everything works as expected.
-
Start the Azure Functions runtime locally:
You should see output indicating your functions are running, typically on
http://localhost:7071
. And you should see the URLs for each function: -
To test the functions, you can use
curl
or a tool like Postman.First, create a test user in your database:
Note the returned
user_id
(let's say it's 1) and use it to test the referral code generation:You should receive a response like:
Check the response for the generated referral code and expiration date.
Verify in the database:
-
With the referral code in hand, test the referral processing function.
Using the referral code from the previous step:
If the referral is successful, you should see:
Otherwise, check the response for error messages from the function.
Verify the changes in the database:
-
Next, test the referral statistics function.
Using the original user's ID:
You should see something like:
-
You can also test error conditions to ensure your functions handle them correctly.
Test invalid referral code:
Test duplicate referral by using the same email:
-
The Azure Functions runtime will output logs to your terminal.
Watch for any errors or debugging information as you test:
If you encounter any issues, you can check the function logs or query the database directly to understand what's happening. Common issues might include:
If you need to, you can reset the test data in your database state by running the following SQL commands to delete the test data:
After testing your functions locally, you're ready to deploy them to Azure.
Deploying to Azure
Deploying your referral system to Azure involves three main steps:
- Create Azure Resources
- Configure Application Settings
- Deploy Your Functions
Let's walk through each step.
Step 1: Create Azure Resources
First, you need to create the necessary resources in Azure: a resource group, a storage account, and a Function App.
-
Log in to Azure CLI:
Follow the instructions to authenticate with your Azure account and select the appropriate subscription.
-
Create a resource group:
This command creates a new resource group named
referral-system
in the East US 2 region. You can choose a different region if needed. A resource group is a logical container for your Azure resources and helps you manage them together more efficiently for billing, access control, and monitoring. -
Create a storage account:
Azure Functions requires a storage account to store logs and runtime state.
Make sure to replace
referral-storage-unique-name
with a unique name for your storage account. Otherwise, the command will fail. -
Create the Function App:
Use the following command to create a Function App running Node.js 18 on the Consumption Plan:
Replace
referral-system
with your desired Function App name andreferral-storage-unique-name
with your storage account name.
Step 2: Configure Application Settings
After creating the Function App, you need to configure it to connect to your Neon database by setting environment variables.
-
Set the
NEON_CONNECTION_STRING
using the Azure CLI: -
Alternative: Configure settings in the Azure Portal:
- Go to your Function App in the Azure Portal.
- Select Configuration under the Settings section.
- Add a new application setting:
- Name:
NEON_CONNECTION_STRING
- Value:
postgres://user:password@ep-xyz.region.azure.neon.tech/neondb
- Name:
- Save your changes.
Step 3: Deploy Your Functions
With everything set up, you can now deploy your functions to Azure directly from Visual Studio Code.
- Open VS Code and press
F1
to open the command palette. - Search for and select Azure sign in to authenticate with your Azure account.
- Then again press
F1
to open the command palette. - Search for and select Azure Functions: Deploy to Function App....
- Select your Azure subscription.
- Choose the Function App (
referral-system
) you created earlier. - Click Deploy when prompted.
You'll see a notification in VS Code once the deployment is successful but it may take a few minutes to complete.
Step 4: Verify the Deployment
After deploying your functions, test them to ensure they're working correctly.
-
Retrieve the function URL:
Use the Azure CLI to get the URL for your
generateReferralCode
function: -
Test the function:
Replace
<function-url>
with the URL returned from the previous step:
Performance Optimization
With your referral system deployed to Azure, you should consider some standard performance optimizations to make sure it scales well under load.
-
Add indexes to frequently queried columns:
You can learn more about indexing in the Neon documentation.
-
Implement connection pooling in your database utility:
Alternatively, you can use the Neon connection pool feature to manage connections efficiently.
-
On the Azure Functions side, consider enabling Azure Functions Premium Plan, which offers more control over scaling and performance.
Cleaning Up Azure Resources (Optional)
If you no longer need the Azure resources created for this project, you can delete them to avoid incurring any charges.
-
Deleting the resource group will remove all associated resources, including the Function App, storage account, and any other resources within the group:
- The
--yes
flag skips the confirmation prompt. - The
--no-wait
flag allows the command to run asynchronously.
- The
-
To verify the deletion:
- Log in to the Azure Portal.
- Navigate to Resource Groups and confirm that the
referral-system
group is no longer listed.
Conclusion
You now have a scalable referral system built with Neon Postgres and Azure Functions. The system handles referral code generation, tracks successful referrals, awards points, and provides referral statistics.
As a next step, you can add more features to your referral system, such as authentication, email notifications, and user dashboards.
Additional Resources
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.