Cloudflare Workers
This guide explains how to connect Cloudflare Workers to an existing Postgres, MySQL, MariaDB or MS SQL Server database via a PolyScale.ai database cache.
When working with Cloudflare Workers, the addition of PolyScale can dramatically increase database performance. It does this by intelligently caching data, close to the Cloudflare Worker. This has two primary benefits: decrease database query execution times (all cached queries execute sub-millisecond) and dramatically reduce network latency by being physically closer, for faster connectivity and data transfer. PolyScale is particularly attractive to use in conjunction with Cloudflare Workers because they can be executed from global locations.


Connection Options
Cloudflare presently has two methods to connect to databases:
- TCP Socket API: A direct TCP connection to a database.
- HTTP or WebSocket-based serverless drivers
Either of these options can be used to connect to a database via PolyScale, but in most use cases the HTTP based PolyScale Serverless API will be preferable. The instructions below illustrate how to connect Cloudflare Workers to your database by either method.
Connecting from Cloudflare Workers via TCP
Step 1: Create PolyScale Cache
Regardless of which connection method you plan to use, the first step is to create a PolyScale cache. Before creating your cache, make sure you have your current database hostname
and port
, as you will need them to set up PolyScale.
- In your PolyScale account, click on the New Cache button
- Give the cache a Name
- Select the Type of database you have
- Enter the Host address for your existing database
- Enter the Port used for your existing database
- Click Create
Once created, PolyScale will automatically run a network test to ensure it can make a TCP connection to your database from all edge network regions. If you see any locations that cannot connect, you can add their source IP's to your database IP Allow List.
You now have a working database cache configured.
PolyScale will automatically run a network connectivity test to ensure your database is accessible from all PolyScale PoPs. Be sure that you have added PolyScale's source IP addresses to your allow-list. You can read more here.
Step 2: Connect to your PolyScale Cache
Using your PolyScale cache is simple -- instead of the Worker connecting to your database directly, you'll replace your database connection string with the PolyScale connection string, within the Worker. Then, all database traffic passes through PolyScale, and then on to the database.
Postgres Example
The PolyScale connection string can always be found within the user interface user the cache Connect
tab. The connection string differs depending upon what database you are connecting to.
With Postgres for example, the cacheId
is appended to the connection string using the application_name
parameter:
Your PolyScale connection string might be: postgres://[USERNAME]]:[PASSWORD]@psedge.global:5432/[DATABASE]]?application_name=[CACHE_ID]
You can read more about how to connect to each database here.
To make a TCP connection from a Cloudflare worker, first install the Node Postgres client:
npm install pg
Them simply use the PolyScale connection string in your Worker:
import { Client } from "pg";
export interface Env {
POLYSCALE_CONN: string;
}
export default {
async fetch(
request: Request,
env: Env,
ctx: ExecutionContext
): Promise<Response> {
const client = new PGClient(env.POLYSCALE_CONN);
await client.connect();
const result = await client.query({
text: "SELECT 1;",
});
const resp = Response.json(result.rows);
ctx.waitUntil(client.end());
return resp;
};
You can then use Wrangler secrets to securely store your database credentials. To do this, create a secret in your Cloudflare Workers project using the following wrangler secret
command:
wrangler secret put POLYSCALE_CONN
See Cloudflare Docs here for complete documentation of the wrangler secret
command.
Deploy your Worker with
wrangler deploy
That's it. Now your Cloudflare Worker is connected to PolyScale via TCP. Database queries will be automatically cached (unless configured otherwise) to speed up query execution times and lower network latency.
Connecting from Cloudflare workers via Serverless API
PolyScale also provides a lightweight HTTP Serverless API, designed for use with Workers. To get connected, follow the below steps.
Step 1: Create A PolyScale Cache
Follow the same instructions above to create your cache.
Step 2: Connect to your PolyScale Cache
This connection method uses the PolyScale Serverless Client to connect from your Cloudflare Worker to PolyScale. You can find an example Cloudflare Worker function using the Serverless Client here, or see the code below.
First install the PolyScale Serverless Client
npm install @polyscale/serverless-js
Then use the following code in your Worker
import { Client } from "@polyscale/serverless-js";
export interface Env {
POLYSCALE_CONN: string;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const polyscale = new Client("https://serverless.aws.polyscale.global", {
cacheId: env.CACHE_ID,
username: env.USERNAME,
password: env.PASSWORD,
database: env.DATABASE,
provider: "mysql",
});
const result = await polyscale.query(
"SELECT emp_no, first_name, last_name FROM employees LIMIT 1;"
);
return new Response(JSON.stringify(result));
},
};
You can then use Wrangler secrets to securely store your database credentials. To easily upload bulk store credentials, create a .json
file like this:
postgres://[USERNAME]]:[PASSWORD]@psedge.global:5432/[DATABASE]]?application_name=[CACHE_ID]
//secrets.json
{
"CACHE_ID": "MY_CACHE_ID",
"USERNAME": "MY_DB_USER",
"PASSWORD": "MY_DB_PASS"
"DATABASE": "MY_DB_NAME"
}
Then use the following wrangler secret:bulk
command:
wrangler secret:bulk secrets.json
See Cloudflare Docs here for complete documentation of the wrangler secret:bulk
command.
wrangler deploy
That's it. Now your Cloudflare Worker is connected to PolyScale. Database queries will be automatically cached (unless configured otherwise) to speed up query execution times and lower network latency.
Using PolyScale Serverless, you can connect any database supported by PolyScale to your Cloudflare worker function, not just a Postgres database.