PG_NET

A PostgreSQL extension that enables asynchronous (non-blocking) HTTP/HTTPS requests with SQL.

Requires libcurl >= 7.83. Compatible with PostgreSQL > = 12.

PostgreSQL versionLicenseCoverage StatusTests


Contents


Introduction

The PG_NET extension enables PostgreSQL to make asynchronous HTTP/HTTPS requests in SQL. It eliminates the need for servers to continuously poll for database changes and instead allows the database to proactively notify external resources about significant events. It seamlessly integrates with triggers, cron jobs (e.g., PG_CRON), and procedures, unlocking numerous possibilities. Notably, PG_NET powers Supabase's Webhook functionality, highlighting its robustness and reliability.

Common use cases for the PG_NET extension include:

  • Calling external APIs
  • Syncing data with outside resources
  • Calling a serverless function when an event, such as an insert, occurred

However, it is important to note that the extension has a few limitations. Currently, it only supports three types of asynchronous requests:

  • async http GET requests
  • async http POST requests with a JSON payload
  • async http DELETE requests

Ultimately, though, PG_NET offers developers more flexibility in how they monitor and connect their database with external resources.


Technical Explanation

The extension introduces a new net schema, which contains two unlogged tables, a type of table in PostgreSQL that offers performance improvements at the expense of durability. You can read more about unlogged tables here. The two tables are:

  1. http_request_queue: This table serves as a queue for requests waiting to be executed. Upon successful execution of a request, the corresponding data is removed from the queue.

    The SQL statement to create this table is:

    CREATE UNLOGGED TABLE
    net.http_request_queue (
    id bigintNOT NULL DEFAULT nextval('net.http_request_queue_id_seq'::regclass),
    method textNOT NULL,
    url textNOT NULL,
    headers jsonb,
    body bytea,
    timeout_milliseconds integerNOT NULL
    )
  2. _http_response: This table holds the responses of each executed request.

    The SQL statement to create this table is:

    CREATE UNLOGGED TABLE
    net._http_response (
    id bigintNULL,
    status_code integerNULL,
    content_type textNULL,
    headers jsonb NULL,
    content textNULL,
    timed_out booleanNULL,
    error_msg textNULL,
    created timestamp with time zoneNOT NULL DEFAULT now()
    )

When any of the three request functions (http_get, http_post, http_delete) are invoked, they create an entry in the net.http_request_queue table.

Once a response is received, it gets stored in the _http_response table. By monitoring this table, you can keep track of response statuses and messages.

Important

Inserting directly into the net.http_request_queue won't cause the worker to process requests, you must use the request functions. We do it this way to avoid polling the net.http_request_queue table, which would pollute pg_stat_statements and cause unnecesssary activity from the worker.

The extension employs C's libcurl library within a PostgreSQL background worker to manage HTTP requests. This background worker sleeps until it receives a signal from the request functions, which awakes it and prompts it to read the net.http_request_queue table and execute the requests on it.


Installation

Clone this repo and run

make && make install

To make the extension available to the database add on postgresql.conf:

shared_preload_libraries = 'pg_net'

By default, pg_net is available on the postgres database. To use pg_net on a different database, you can add the following on postgresql.conf:

pg_net.database_name = '<dbname>';

Using pg_net on multiple databases in a cluster is not yet supported.

To activate the extension in PostgreSQL, run the create extension command. The extension creates its own schema named net to avoid naming conflicts.

create extension pg_net;

Extension Configuration

The extension creates the following configurable variables:

  1. pg_net.batch_size(default: 200): An integer that limits the max number of rows that the extension will process from net.http_request_queue during each read
  2. pg_net.ttl(default: 6 hours): An interval that defines the max time a row in the net.http_response will live before being deleted. Note that this won't happen exactly after the TTL has passed. The worker will perform this deletion while its processing requests.
  3. pg_net.database_name(default: 'postgres'): A string that defines which database the extension is applied to
  4. pg_net.username(default: NULL): A string that defines which user will the background worker be connected with. If not set (NULL), it will assume the bootstrap user.

All these variables can be viewed with the following commands:

show pg_net.batch_size;
show pg_net.ttl;
show pg_net.database_name;
show pg_net.username;

You can change these by editing the postgresql.conf file (find it with SHOW config_file;) or with ALTER SYSTEM:

alter system set pg_net.ttl to '1 hour'
alter system set pg_net.batch_size to 500;

Then, you can reload the settings with:

select pg_reload_conf();

If you change the pg_net.database_name and pg_net.username configs, you'll need to restart the worker for them to apply. We provide a function that reloads the config with pg_reload_conf and restarts the worker in one go:

select net.worker_restart();

Note that doing ALTER SYSTEM requires SUPERUSER but on PostgreSQL >= 15, you can do:

grant alter system on parameter pg_net.ttl to <role>;
grant alter system on parameter pg_net.batch_size to <role>;

To allow regular users to update pg_net settings.

Requests API

GET requests

net.http_get function signature

net.http_get(
-- url for the request
url text,
-- key/value pairs to be url encoded and appended to the `url`
params jsonb default '{}'::jsonb,
-- key/values to be included in request headers
headers jsonb default '{}'::jsonb,
-- the maximum number of milliseconds the request may take before being cancelled
timeout_milliseconds int default 1000
)
-- request_id reference
returns bigint
strict
volatile
parallel safe
language plpgsql

Examples:

The following examples use the Postman Echo API.

Calling an API

SELECTnet.http_get (
'https://postman-echo.com/get?foo1=bar1&foo2=bar2'
) AS request_id;

NOTE: You can view the response with the following query:

SELECT*FROMnet._http_response;

Calling an API with URL encoded params

SELECTnet.http_get(
'https://postman-echo.com/get',
-- Equivalent to calling https://postman-echo.com/get?foo1=bar1&foo2=bar2&encoded=%21-- The "!" is url-encoded as %21'{"foo1": "bar1", "foo2": "bar2", "encoded": "!"}'::JSONB
) AS request_id;

Calling an API with an API-KEY

SELECTnet.http_get(
'https://postman-echo.com/get?foo1=bar1&foo2=bar2',
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id;

POST requests

net.http_post function signature

net.http_post(
-- url for the request
url text,
-- body of the POST request
body jsonb default '{}'::jsonb,
-- key/value pairs to be url encoded and appended to the `url`
params jsonb default '{}'::jsonb,
-- key/values to be included in request headers
headers jsonb default '{"Content-Type": "application/json"}'::jsonb,
-- the maximum number of milliseconds the request may take before being cancelled
timeout_milliseconds int default 1000
)
-- request_id reference
returns bigint
volatile
parallel safe
language plpgsql

Examples:

The following examples post to the Postman Echo API.

Sending data to an API

SELECTnet.http_post(
'https://postman-echo.com/post',
'{"key": "value", "key": 5}'::JSONB,
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id;

Sending single table row as a payload

NOTE: If multiple rows are sent using this method, each row will be sent as a separate request.

WITH selected_row AS (
SELECT*FROM target_table
LIMIT1
)
SELECTnet.http_post(
'https://postman-echo.com/post',
to_jsonb(selected_row.*),
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id
FROM selected_row;

Sending multiple table rows as a payload

WARNING: when sending multiple rows, be careful to limit your payload size.

WITH selected_rows AS (
SELECT-- Converts all the rows into a JSONB array
jsonb_agg(to_jsonb(target_table)) AS JSON_payload
FROM target_table
-- Generally good practice to LIMIT the max amount of rows
)
SELECTnet.http_post(
'https://postman-echo.com/post'::TEXT,
JSON_payload,
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id
FROM selected_rows;

DELETE requests

net.http_delete function signature

net.http_delete(
-- url for the request
url text,
-- key/value pairs to be url encoded and appended to the `url`
params jsonb default '{}'::jsonb,
-- key/values to be included in request headers
headers jsonb default '{}'::jsonb,
-- the maximum number of milliseconds the request may take before being cancelled
timeout_milliseconds int default 2000
)
-- request_id reference
returns bigint
strict
volatile
parallel safe
language plpgsql
security definer

Examples:

The following examples use the Dummy Rest API.

Sending a delete request to an API

SELECTnet.http_delete(
'https://dummy.restapiexample.com/api/v1/delete/2'
) AS request_id;

Sending a delete request with a row id as a query param

WITH selected_id AS (
SELECT
id
FROM target_table
LIMIT1-- if not limited, it will make a delete request for each returned row
)
SELECTnet.http_delete(
'https://dummy.restapiexample.com/api/v1/delete/'::TEXT,
format('{"id": "%s"}', id)::JSONB
) AS request_id
FROM selected_id;

Sending a delete request with a row id as a path param

WITH selected_id AS (
SELECT
id
FROM target_table
LIMIT1-- if not limited, it will make a delete request for each returned row
)
SELECTnet.http_delete(
'https://dummy.restapiexample.com/api/v1/delete/'|| id
) AS request_id
FROM selected_row

Practical Examples

Syncing data with an external data source using triggers

The following example comes from Typesense's Supabase Sync guide

-- Create the function to delete the record from TypesenseCREATE OR REPLACEFUNCTIONdelete_record()
RETURNS TRIGGER
LANGUAGE plpgSQL
AS $$
BEGINSELECTnet.http_delete(
url := format('<TYPESENSE URL>/collections/products/documents/%s', OLD.id),
headers :='{"X-Typesense-API-KEY": "<Typesense_API_KEY>"}'
)
RETURN OLD;
END $$;
-- Create the trigger that calls the function when a record is deleted from the products tableCREATETRIGGERdelete_products_trigger
AFTER DELETEONpublic.products
FOR EACH ROW
EXECUTE FUNCTION delete_products();

Calling a serverless function every minute with PG_CRON

The PG_CRON extension enables PostgreSQL to become its own cron server. With it you can schedule regular calls to activate serverless functions.

Useful links:

Example Cron job to call serverless function

SELECTcron.schedule(
'cron-job-name',
'* * * * *', -- Executes every minute (cron syntax)
$$
-- SQL querySELECTnet.http_get(
-- URL of Edge function
url:='https://<reference id>.functions.supabase.co/example',
headers:='{ "Content-Type": "application/json", "Authorization": "Bearer <TOKEN>" }'::JSONB
) as request_id;
$$
);

Retrying failed requests

Every request made is logged within the net._http_response table. To identify failed requests, you can execute a query on the table, filtering for requests where the status code is 500 or higher.

Finding failed requests

SELECT*FROMnet._http_responseWHERE status_code >=500;

While the net._http_response table logs each request, it doesn't store all the necessary information to retry failed requests. To facilitate this, we need to create a request tracking table and a wrapper function around the PG_NET request functions. This will help us store the required details for each request.

Creating a Request Tracker Table

CREATETABLErequest_tracker(
method TEXT,
url TEXT,
params JSONB,
body JSONB,
headers JSONB,
request_id BIGINT
)

Below is a function called request_wrapper, which wraps around the PG_NET request functions. This function records every request's details in the request_tracker table, facilitating future retries if needed.

Creating a Request Wrapper Function

CREATE OR REPLACEFUNCTIONrequest_wrapper(
method TEXT,
url TEXT,
params JSONB DEFAULT '{}'::JSONB,
body JSONB DEFAULT '{}'::JSONB,
headers JSONB DEFAULT '{}'::JSONB
)
RETURNS BIGINTAS $$
DECLARE
request_id BIGINT;
BEGIN
IF method ='DELETE' THEN
SELECTnet.http_delete(
url:=url,
params:=params,
headers:=headers
) INTO request_id;
ELSIF method ='POST' THEN
SELECTnet.http_post(
url:=url,
body:=body,
params:=params,
headers:=headers
) INTO request_id;
ELSIF method ='GET' THEN
SELECTnet.http_get(
url:=url,
params:=params,
headers:=headers
) INTO request_id;
ELSE
RAISE EXCEPTION 'Method must be DELETE, POST, or GET';
END IF;
INSERT INTO request_tracker (method, url, params, body, headers, request_id)
VALUES (method, url, params, body, headers, request_id);
RETURN request_id;
END;
$$
LANGUAGE plpgsql;

To retry a failed request recorded via the wrapper function, use the following query. This will select failed requests, retry them, and then remove the original request data from both the net._http_response and request_tracker tables.

Retrying failed requests

WITH retry_request AS (
SELECTrequest_tracker.method,
request_tracker.url,
request_tracker.params,
request_tracker.body,
request_tracker.headers,
request_tracker.request_idFROM request_tracker
INNER JOINnet._http_responseONnet._http_response.id =request_tracker.request_idWHEREnet._http_response.status_code >=500LIMIT3
),
retry AS (
SELECT
request_wrapper(retry_request.method, retry_request.url, retry_request.params, retry_request.body, retry_request.headers)
FROM retry_request
),
delete_http_response AS (
DELETEFROMnet._http_responseWHERE id IN (SELECT request_id FROM retry_request)
RETURNING *
)
DELETEFROM request_tracker
WHERE request_id IN (SELECT request_id FROM retry_request)
RETURNING *;

The above function can be called using cron jobs or manually to retry failed requests. It may also be beneficial to clean the request_tracker table in the process.

Contributing

Checkout the Contributing page to learn more about adding to the project.

About

A PostgreSQL extension that enables asynchronous (non-blocking) HTTP/HTTPS requests with SQL

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

368 stars

Watchers

27 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

PG_NET

A PostgreSQL extension that enables asynchronous (non-blocking) HTTP/HTTPS requests with SQL.

Requires libcurl >= 7.83. Compatible with PostgreSQL > = 12.

PostgreSQL versionLicenseCoverage StatusTests


Contents


Introduction

The PG_NET extension enables PostgreSQL to make asynchronous HTTP/HTTPS requests in SQL. It eliminates the need for servers to continuously poll for database changes and instead allows the database to proactively notify external resources about significant events. It seamlessly integrates with triggers, cron jobs (e.g., PG_CRON), and procedures, unlocking numerous possibilities. Notably, PG_NET powers Supabase's Webhook functionality, highlighting its robustness and reliability.

Common use cases for the PG_NET extension include:

  • Calling external APIs
  • Syncing data with outside resources
  • Calling a serverless function when an event, such as an insert, occurred

However, it is important to note that the extension has a few limitations. Currently, it only supports three types of asynchronous requests:

  • async http GET requests
  • async http POST requests with a JSON payload
  • async http DELETE requests

Ultimately, though, PG_NET offers developers more flexibility in how they monitor and connect their database with external resources.


Technical Explanation

The extension introduces a new net schema, which contains two unlogged tables, a type of table in PostgreSQL that offers performance improvements at the expense of durability. You can read more about unlogged tables here. The two tables are:

  1. http_request_queue: This table serves as a queue for requests waiting to be executed. Upon successful execution of a request, the corresponding data is removed from the queue.

    The SQL statement to create this table is:

    CREATE UNLOGGED TABLE
    net.http_request_queue (
    id bigintNOT NULL DEFAULT nextval('net.http_request_queue_id_seq'::regclass),
    method textNOT NULL,
    url textNOT NULL,
    headers jsonb,
    body bytea,
    timeout_milliseconds integerNOT NULL
    )
  2. _http_response: This table holds the responses of each executed request.

    The SQL statement to create this table is:

    CREATE UNLOGGED TABLE
    net._http_response (
    id bigintNULL,
    status_code integerNULL,
    content_type textNULL,
    headers jsonb NULL,
    content textNULL,
    timed_out booleanNULL,
    error_msg textNULL,
    created timestamp with time zoneNOT NULL DEFAULT now()
    )

When any of the three request functions (http_get, http_post, http_delete) are invoked, they create an entry in the net.http_request_queue table.

Once a response is received, it gets stored in the _http_response table. By monitoring this table, you can keep track of response statuses and messages.

Important

Inserting directly into the net.http_request_queue won't cause the worker to process requests, you must use the request functions. We do it this way to avoid polling the net.http_request_queue table, which would pollute pg_stat_statements and cause unnecesssary activity from the worker.

The extension employs C's libcurl library within a PostgreSQL background worker to manage HTTP requests. This background worker sleeps until it receives a signal from the request functions, which awakes it and prompts it to read the net.http_request_queue table and execute the requests on it.


Installation

Clone this repo and run

make && make install

To make the extension available to the database add on postgresql.conf:

shared_preload_libraries = 'pg_net'

By default, pg_net is available on the postgres database. To use pg_net on a different database, you can add the following on postgresql.conf:

pg_net.database_name = '<dbname>';

Using pg_net on multiple databases in a cluster is not yet supported.

To activate the extension in PostgreSQL, run the create extension command. The extension creates its own schema named net to avoid naming conflicts.

create extension pg_net;

Extension Configuration

The extension creates the following configurable variables:

  1. pg_net.batch_size(default: 200): An integer that limits the max number of rows that the extension will process from net.http_request_queue during each read
  2. pg_net.ttl(default: 6 hours): An interval that defines the max time a row in the net.http_response will live before being deleted. Note that this won't happen exactly after the TTL has passed. The worker will perform this deletion while its processing requests.
  3. pg_net.database_name(default: 'postgres'): A string that defines which database the extension is applied to
  4. pg_net.username(default: NULL): A string that defines which user will the background worker be connected with. If not set (NULL), it will assume the bootstrap user.

All these variables can be viewed with the following commands:

show pg_net.batch_size;
show pg_net.ttl;
show pg_net.database_name;
show pg_net.username;

You can change these by editing the postgresql.conf file (find it with SHOW config_file;) or with ALTER SYSTEM:

alter system set pg_net.ttl to '1 hour'
alter system set pg_net.batch_size to 500;

Then, you can reload the settings with:

select pg_reload_conf();

If you change the pg_net.database_name and pg_net.username configs, you'll need to restart the worker for them to apply. We provide a function that reloads the config with pg_reload_conf and restarts the worker in one go:

select net.worker_restart();

Note that doing ALTER SYSTEM requires SUPERUSER but on PostgreSQL >= 15, you can do:

grant alter system on parameter pg_net.ttl to <role>;
grant alter system on parameter pg_net.batch_size to <role>;

To allow regular users to update pg_net settings.

Requests API

GET requests

net.http_get function signature

net.http_get(
-- url for the request
url text,
-- key/value pairs to be url encoded and appended to the `url`
params jsonb default '{}'::jsonb,
-- key/values to be included in request headers
headers jsonb default '{}'::jsonb,
-- the maximum number of milliseconds the request may take before being cancelled
timeout_milliseconds int default 1000
)
-- request_id reference
returns bigint
strict
volatile
parallel safe
language plpgsql

Examples:

The following examples use the Postman Echo API.

Calling an API

SELECTnet.http_get (
'https://postman-echo.com/get?foo1=bar1&foo2=bar2'
) AS request_id;

NOTE: You can view the response with the following query:

SELECT*FROMnet._http_response;

Calling an API with URL encoded params

SELECTnet.http_get(
'https://postman-echo.com/get',
-- Equivalent to calling https://postman-echo.com/get?foo1=bar1&foo2=bar2&encoded=%21-- The "!" is url-encoded as %21'{"foo1": "bar1", "foo2": "bar2", "encoded": "!"}'::JSONB
) AS request_id;

Calling an API with an API-KEY

SELECTnet.http_get(
'https://postman-echo.com/get?foo1=bar1&foo2=bar2',
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id;

POST requests

net.http_post function signature

net.http_post(
-- url for the request
url text,
-- body of the POST request
body jsonb default '{}'::jsonb,
-- key/value pairs to be url encoded and appended to the `url`
params jsonb default '{}'::jsonb,
-- key/values to be included in request headers
headers jsonb default '{"Content-Type": "application/json"}'::jsonb,
-- the maximum number of milliseconds the request may take before being cancelled
timeout_milliseconds int default 1000
)
-- request_id reference
returns bigint
volatile
parallel safe
language plpgsql

Examples:

The following examples post to the Postman Echo API.

Sending data to an API

SELECTnet.http_post(
'https://postman-echo.com/post',
'{"key": "value", "key": 5}'::JSONB,
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id;

Sending single table row as a payload

NOTE: If multiple rows are sent using this method, each row will be sent as a separate request.

WITH selected_row AS (
SELECT*FROM target_table
LIMIT1
)
SELECTnet.http_post(
'https://postman-echo.com/post',
to_jsonb(selected_row.*),
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id
FROM selected_row;

Sending multiple table rows as a payload

WARNING: when sending multiple rows, be careful to limit your payload size.

WITH selected_rows AS (
SELECT-- Converts all the rows into a JSONB array
jsonb_agg(to_jsonb(target_table)) AS JSON_payload
FROM target_table
-- Generally good practice to LIMIT the max amount of rows
)
SELECTnet.http_post(
'https://postman-echo.com/post'::TEXT,
JSON_payload,
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id
FROM selected_rows;

DELETE requests

net.http_delete function signature

net.http_delete(
-- url for the request
url text,
-- key/value pairs to be url encoded and appended to the `url`
params jsonb default '{}'::jsonb,
-- key/values to be included in request headers
headers jsonb default '{}'::jsonb,
-- the maximum number of milliseconds the request may take before being cancelled
timeout_milliseconds int default 2000
)
-- request_id reference
returns bigint
strict
volatile
parallel safe
language plpgsql
security definer

Examples:

The following examples use the Dummy Rest API.

Sending a delete request to an API

SELECTnet.http_delete(
'https://dummy.restapiexample.com/api/v1/delete/2'
) AS request_id;

Sending a delete request with a row id as a query param

WITH selected_id AS (
SELECT
id
FROM target_table
LIMIT1-- if not limited, it will make a delete request for each returned row
)
SELECTnet.http_delete(
'https://dummy.restapiexample.com/api/v1/delete/'::TEXT,
format('{"id": "%s"}', id)::JSONB
) AS request_id
FROM selected_id;

Sending a delete request with a row id as a path param

WITH selected_id AS (
SELECT
id
FROM target_table
LIMIT1-- if not limited, it will make a delete request for each returned row
)
SELECTnet.http_delete(
'https://dummy.restapiexample.com/api/v1/delete/'|| id
) AS request_id
FROM selected_row

Practical Examples

Syncing data with an external data source using triggers

The following example comes from Typesense's Supabase Sync guide

-- Create the function to delete the record from TypesenseCREATE OR REPLACEFUNCTIONdelete_record()
RETURNS TRIGGER
LANGUAGE plpgSQL
AS $$
BEGINSELECTnet.http_delete(
url := format('<TYPESENSE URL>/collections/products/documents/%s', OLD.id),
headers :='{"X-Typesense-API-KEY": "<Typesense_API_KEY>"}'
)
RETURN OLD;
END $$;
-- Create the trigger that calls the function when a record is deleted from the products tableCREATETRIGGERdelete_products_trigger
AFTER DELETEONpublic.products
FOR EACH ROW
EXECUTE FUNCTION delete_products();

Calling a serverless function every minute with PG_CRON

The PG_CRON extension enables PostgreSQL to become its own cron server. With it you can schedule regular calls to activate serverless functions.

Useful links:

Example Cron job to call serverless function

SELECTcron.schedule(
'cron-job-name',
'* * * * *', -- Executes every minute (cron syntax)
$$
-- SQL querySELECTnet.http_get(
-- URL of Edge function
url:='https://<reference id>.functions.supabase.co/example',
headers:='{ "Content-Type": "application/json", "Authorization": "Bearer <TOKEN>" }'::JSONB
) as request_id;
$$
);

Retrying failed requests

Every request made is logged within the net._http_response table. To identify failed requests, you can execute a query on the table, filtering for requests where the status code is 500 or higher.

Finding failed requests

SELECT*FROMnet._http_responseWHERE status_code >=500;

While the net._http_response table logs each request, it doesn't store all the necessary information to retry failed requests. To facilitate this, we need to create a request tracking table and a wrapper function around the PG_NET request functions. This will help us store the required details for each request.

Creating a Request Tracker Table

CREATETABLErequest_tracker(
method TEXT,
url TEXT,
params JSONB,
body JSONB,
headers JSONB,
request_id BIGINT
)

Below is a function called request_wrapper, which wraps around the PG_NET request functions. This function records every request's details in the request_tracker table, facilitating future retries if needed.

Creating a Request Wrapper Function

CREATE OR REPLACEFUNCTIONrequest_wrapper(
method TEXT,
url TEXT,
params JSONB DEFAULT '{}'::JSONB,
body JSONB DEFAULT '{}'::JSONB,
headers JSONB DEFAULT '{}'::JSONB
)
RETURNS BIGINTAS $$
DECLARE
request_id BIGINT;
BEGIN
IF method ='DELETE' THEN
SELECTnet.http_delete(
url:=url,
params:=params,
headers:=headers
) INTO request_id;
ELSIF method ='POST' THEN
SELECTnet.http_post(
url:=url,
body:=body,
params:=params,
headers:=headers
) INTO request_id;
ELSIF method ='GET' THEN
SELECTnet.http_get(
url:=url,
params:=params,
headers:=headers
) INTO request_id;
ELSE
RAISE EXCEPTION 'Method must be DELETE, POST, or GET';
END IF;
INSERT INTO request_tracker (method, url, params, body, headers, request_id)
VALUES (method, url, params, body, headers, request_id);
RETURN request_id;
END;
$$
LANGUAGE plpgsql;

To retry a failed request recorded via the wrapper function, use the following query. This will select failed requests, retry them, and then remove the original request data from both the net._http_response and request_tracker tables.

Retrying failed requests

WITH retry_request AS (
SELECTrequest_tracker.method,
request_tracker.url,
request_tracker.params,
request_tracker.body,
request_tracker.headers,
request_tracker.request_idFROM request_tracker
INNER JOINnet._http_responseONnet._http_response.id =request_tracker.request_idWHEREnet._http_response.status_code >=500LIMIT3
),
retry AS (
SELECT
request_wrapper(retry_request.method, retry_request.url, retry_request.params, retry_request.body, retry_request.headers)
FROM retry_request
),
delete_http_response AS (
DELETEFROMnet._http_responseWHERE id IN (SELECT request_id FROM retry_request)
RETURNING *
)
DELETEFROM request_tracker
WHERE request_id IN (SELECT request_id FROM retry_request)
RETURNING *;

The above function can be called using cron jobs or manually to retry failed requests. It may also be beneficial to clean the request_tracker table in the process.

Contributing

Checkout the Contributing page to learn more about adding to the project.

About

A PostgreSQL extension that enables asynchronous (non-blocking) HTTP/HTTPS requests with SQL

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

368 stars

Watchers

27 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

PG_NET

A PostgreSQL extension that enables asynchronous (non-blocking) HTTP/HTTPS requests with SQL.

Requires libcurl >= 7.83. Compatible with PostgreSQL > = 12.

PostgreSQL versionLicenseCoverage StatusTests


Contents


Introduction

The PG_NET extension enables PostgreSQL to make asynchronous HTTP/HTTPS requests in SQL. It eliminates the need for servers to continuously poll for database changes and instead allows the database to proactively notify external resources about significant events. It seamlessly integrates with triggers, cron jobs (e.g., PG_CRON), and procedures, unlocking numerous possibilities. Notably, PG_NET powers Supabase's Webhook functionality, highlighting its robustness and reliability.

Common use cases for the PG_NET extension include:

  • Calling external APIs
  • Syncing data with outside resources
  • Calling a serverless function when an event, such as an insert, occurred

However, it is important to note that the extension has a few limitations. Currently, it only supports three types of asynchronous requests:

  • async http GET requests
  • async http POST requests with a JSON payload
  • async http DELETE requests

Ultimately, though, PG_NET offers developers more flexibility in how they monitor and connect their database with external resources.


Technical Explanation

The extension introduces a new net schema, which contains two unlogged tables, a type of table in PostgreSQL that offers performance improvements at the expense of durability. You can read more about unlogged tables here. The two tables are:

  1. http_request_queue: This table serves as a queue for requests waiting to be executed. Upon successful execution of a request, the corresponding data is removed from the queue.

    The SQL statement to create this table is:

    CREATE UNLOGGED TABLE
    net.http_request_queue (
    id bigintNOT NULL DEFAULT nextval('net.http_request_queue_id_seq'::regclass),
    method textNOT NULL,
    url textNOT NULL,
    headers jsonb,
    body bytea,
    timeout_milliseconds integerNOT NULL
    )
  2. _http_response: This table holds the responses of each executed request.

    The SQL statement to create this table is:

    CREATE UNLOGGED TABLE
    net._http_response (
    id bigintNULL,
    status_code integerNULL,
    content_type textNULL,
    headers jsonb NULL,
    content textNULL,
    timed_out booleanNULL,
    error_msg textNULL,
    created timestamp with time zoneNOT NULL DEFAULT now()
    )

When any of the three request functions (http_get, http_post, http_delete) are invoked, they create an entry in the net.http_request_queue table.

Once a response is received, it gets stored in the _http_response table. By monitoring this table, you can keep track of response statuses and messages.

Important

Inserting directly into the net.http_request_queue won't cause the worker to process requests, you must use the request functions. We do it this way to avoid polling the net.http_request_queue table, which would pollute pg_stat_statements and cause unnecesssary activity from the worker.

The extension employs C's libcurl library within a PostgreSQL background worker to manage HTTP requests. This background worker sleeps until it receives a signal from the request functions, which awakes it and prompts it to read the net.http_request_queue table and execute the requests on it.


Installation

Clone this repo and run

make && make install

To make the extension available to the database add on postgresql.conf:

shared_preload_libraries = 'pg_net'

By default, pg_net is available on the postgres database. To use pg_net on a different database, you can add the following on postgresql.conf:

pg_net.database_name = '<dbname>';

Using pg_net on multiple databases in a cluster is not yet supported.

To activate the extension in PostgreSQL, run the create extension command. The extension creates its own schema named net to avoid naming conflicts.

create extension pg_net;

Extension Configuration

The extension creates the following configurable variables:

  1. pg_net.batch_size(default: 200): An integer that limits the max number of rows that the extension will process from net.http_request_queue during each read
  2. pg_net.ttl(default: 6 hours): An interval that defines the max time a row in the net.http_response will live before being deleted. Note that this won't happen exactly after the TTL has passed. The worker will perform this deletion while its processing requests.
  3. pg_net.database_name(default: 'postgres'): A string that defines which database the extension is applied to
  4. pg_net.username(default: NULL): A string that defines which user will the background worker be connected with. If not set (NULL), it will assume the bootstrap user.

All these variables can be viewed with the following commands:

show pg_net.batch_size;
show pg_net.ttl;
show pg_net.database_name;
show pg_net.username;

You can change these by editing the postgresql.conf file (find it with SHOW config_file;) or with ALTER SYSTEM:

alter system set pg_net.ttl to '1 hour'
alter system set pg_net.batch_size to 500;

Then, you can reload the settings with:

select pg_reload_conf();

If you change the pg_net.database_name and pg_net.username configs, you'll need to restart the worker for them to apply. We provide a function that reloads the config with pg_reload_conf and restarts the worker in one go:

select net.worker_restart();

Note that doing ALTER SYSTEM requires SUPERUSER but on PostgreSQL >= 15, you can do:

grant alter system on parameter pg_net.ttl to <role>;
grant alter system on parameter pg_net.batch_size to <role>;

To allow regular users to update pg_net settings.

Requests API

GET requests

net.http_get function signature

net.http_get(
-- url for the request
url text,
-- key/value pairs to be url encoded and appended to the `url`
params jsonb default '{}'::jsonb,
-- key/values to be included in request headers
headers jsonb default '{}'::jsonb,
-- the maximum number of milliseconds the request may take before being cancelled
timeout_milliseconds int default 1000
)
-- request_id reference
returns bigint
strict
volatile
parallel safe
language plpgsql

Examples:

The following examples use the Postman Echo API.

Calling an API

SELECTnet.http_get (
'https://postman-echo.com/get?foo1=bar1&foo2=bar2'
) AS request_id;

NOTE: You can view the response with the following query:

SELECT*FROMnet._http_response;

Calling an API with URL encoded params

SELECTnet.http_get(
'https://postman-echo.com/get',
-- Equivalent to calling https://postman-echo.com/get?foo1=bar1&foo2=bar2&encoded=%21-- The "!" is url-encoded as %21'{"foo1": "bar1", "foo2": "bar2", "encoded": "!"}'::JSONB
) AS request_id;

Calling an API with an API-KEY

SELECTnet.http_get(
'https://postman-echo.com/get?foo1=bar1&foo2=bar2',
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id;

POST requests

net.http_post function signature

net.http_post(
-- url for the request
url text,
-- body of the POST request
body jsonb default '{}'::jsonb,
-- key/value pairs to be url encoded and appended to the `url`
params jsonb default '{}'::jsonb,
-- key/values to be included in request headers
headers jsonb default '{"Content-Type": "application/json"}'::jsonb,
-- the maximum number of milliseconds the request may take before being cancelled
timeout_milliseconds int default 1000
)
-- request_id reference
returns bigint
volatile
parallel safe
language plpgsql

Examples:

The following examples post to the Postman Echo API.

Sending data to an API

SELECTnet.http_post(
'https://postman-echo.com/post',
'{"key": "value", "key": 5}'::JSONB,
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id;

Sending single table row as a payload

NOTE: If multiple rows are sent using this method, each row will be sent as a separate request.

WITH selected_row AS (
SELECT*FROM target_table
LIMIT1
)
SELECTnet.http_post(
'https://postman-echo.com/post',
to_jsonb(selected_row.*),
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id
FROM selected_row;

Sending multiple table rows as a payload

WARNING: when sending multiple rows, be careful to limit your payload size.

WITH selected_rows AS (
SELECT-- Converts all the rows into a JSONB array
jsonb_agg(to_jsonb(target_table)) AS JSON_payload
FROM target_table
-- Generally good practice to LIMIT the max amount of rows
)
SELECTnet.http_post(
'https://postman-echo.com/post'::TEXT,
JSON_payload,
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id
FROM selected_rows;

DELETE requests

net.http_delete function signature

net.http_delete(
-- url for the request
url text,
-- key/value pairs to be url encoded and appended to the `url`
params jsonb default '{}'::jsonb,
-- key/values to be included in request headers
headers jsonb default '{}'::jsonb,
-- the maximum number of milliseconds the request may take before being cancelled
timeout_milliseconds int default 2000
)
-- request_id reference
returns bigint
strict
volatile
parallel safe
language plpgsql
security definer

Examples:

The following examples use the Dummy Rest API.

Sending a delete request to an API

SELECTnet.http_delete(
'https://dummy.restapiexample.com/api/v1/delete/2'
) AS request_id;

Sending a delete request with a row id as a query param

WITH selected_id AS (
SELECT
id
FROM target_table
LIMIT1-- if not limited, it will make a delete request for each returned row
)
SELECTnet.http_delete(
'https://dummy.restapiexample.com/api/v1/delete/'::TEXT,
format('{"id": "%s"}', id)::JSONB
) AS request_id
FROM selected_id;

Sending a delete request with a row id as a path param

WITH selected_id AS (
SELECT
id
FROM target_table
LIMIT1-- if not limited, it will make a delete request for each returned row
)
SELECTnet.http_delete(
'https://dummy.restapiexample.com/api/v1/delete/'|| id
) AS request_id
FROM selected_row

Practical Examples

Syncing data with an external data source using triggers

The following example comes from Typesense's Supabase Sync guide

-- Create the function to delete the record from TypesenseCREATE OR REPLACEFUNCTIONdelete_record()
RETURNS TRIGGER
LANGUAGE plpgSQL
AS $$
BEGINSELECTnet.http_delete(
url := format('<TYPESENSE URL>/collections/products/documents/%s', OLD.id),
headers :='{"X-Typesense-API-KEY": "<Typesense_API_KEY>"}'
)
RETURN OLD;
END $$;
-- Create the trigger that calls the function when a record is deleted from the products tableCREATETRIGGERdelete_products_trigger
AFTER DELETEONpublic.products
FOR EACH ROW
EXECUTE FUNCTION delete_products();

Calling a serverless function every minute with PG_CRON

The PG_CRON extension enables PostgreSQL to become its own cron server. With it you can schedule regular calls to activate serverless functions.

Useful links:

Example Cron job to call serverless function

SELECTcron.schedule(
'cron-job-name',
'* * * * *', -- Executes every minute (cron syntax)
$$
-- SQL querySELECTnet.http_get(
-- URL of Edge function
url:='https://<reference id>.functions.supabase.co/example',
headers:='{ "Content-Type": "application/json", "Authorization": "Bearer <TOKEN>" }'::JSONB
) as request_id;
$$
);

Retrying failed requests

Every request made is logged within the net._http_response table. To identify failed requests, you can execute a query on the table, filtering for requests where the status code is 500 or higher.

Finding failed requests

SELECT*FROMnet._http_responseWHERE status_code >=500;

While the net._http_response table logs each request, it doesn't store all the necessary information to retry failed requests. To facilitate this, we need to create a request tracking table and a wrapper function around the PG_NET request functions. This will help us store the required details for each request.

Creating a Request Tracker Table

CREATETABLErequest_tracker(
method TEXT,
url TEXT,
params JSONB,
body JSONB,
headers JSONB,
request_id BIGINT
)

Below is a function called request_wrapper, which wraps around the PG_NET request functions. This function records every request's details in the request_tracker table, facilitating future retries if needed.

Creating a Request Wrapper Function

CREATE OR REPLACEFUNCTIONrequest_wrapper(
method TEXT,
url TEXT,
params JSONB DEFAULT '{}'::JSONB,
body JSONB DEFAULT '{}'::JSONB,
headers JSONB DEFAULT '{}'::JSONB
)
RETURNS BIGINTAS $$
DECLARE
request_id BIGINT;
BEGIN
IF method ='DELETE' THEN
SELECTnet.http_delete(
url:=url,
params:=params,
headers:=headers
) INTO request_id;
ELSIF method ='POST' THEN
SELECTnet.http_post(
url:=url,
body:=body,
params:=params,
headers:=headers
) INTO request_id;
ELSIF method ='GET' THEN
SELECTnet.http_get(
url:=url,
params:=params,
headers:=headers
) INTO request_id;
ELSE
RAISE EXCEPTION 'Method must be DELETE, POST, or GET';
END IF;
INSERT INTO request_tracker (method, url, params, body, headers, request_id)
VALUES (method, url, params, body, headers, request_id);
RETURN request_id;
END;
$$
LANGUAGE plpgsql;

To retry a failed request recorded via the wrapper function, use the following query. This will select failed requests, retry them, and then remove the original request data from both the net._http_response and request_tracker tables.

Retrying failed requests

WITH retry_request AS (
SELECTrequest_tracker.method,
request_tracker.url,
request_tracker.params,
request_tracker.body,
request_tracker.headers,
request_tracker.request_idFROM request_tracker
INNER JOINnet._http_responseONnet._http_response.id =request_tracker.request_idWHEREnet._http_response.status_code >=500LIMIT3
),
retry AS (
SELECT
request_wrapper(retry_request.method, retry_request.url, retry_request.params, retry_request.body, retry_request.headers)
FROM retry_request
),
delete_http_response AS (
DELETEFROMnet._http_responseWHERE id IN (SELECT request_id FROM retry_request)
RETURNING *
)
DELETEFROM request_tracker
WHERE request_id IN (SELECT request_id FROM retry_request)
RETURNING *;

The above function can be called using cron jobs or manually to retry failed requests. It may also be beneficial to clean the request_tracker table in the process.

Contributing

Checkout the Contributing page to learn more about adding to the project.

About

A PostgreSQL extension that enables asynchronous (non-blocking) HTTP/HTTPS requests with SQL

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

368 stars

Watchers

27 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

PG_NET

A PostgreSQL extension that enables asynchronous (non-blocking) HTTP/HTTPS requests with SQL.

Requires libcurl >= 7.83. Compatible with PostgreSQL > = 12.

PostgreSQL versionLicenseCoverage StatusTests


Contents


Introduction

The PG_NET extension enables PostgreSQL to make asynchronous HTTP/HTTPS requests in SQL. It eliminates the need for servers to continuously poll for database changes and instead allows the database to proactively notify external resources about significant events. It seamlessly integrates with triggers, cron jobs (e.g., PG_CRON), and procedures, unlocking numerous possibilities. Notably, PG_NET powers Supabase's Webhook functionality, highlighting its robustness and reliability.

Common use cases for the PG_NET extension include:

  • Calling external APIs
  • Syncing data with outside resources
  • Calling a serverless function when an event, such as an insert, occurred

However, it is important to note that the extension has a few limitations. Currently, it only supports three types of asynchronous requests:

  • async http GET requests
  • async http POST requests with a JSON payload
  • async http DELETE requests

Ultimately, though, PG_NET offers developers more flexibility in how they monitor and connect their database with external resources.


Technical Explanation

The extension introduces a new net schema, which contains two unlogged tables, a type of table in PostgreSQL that offers performance improvements at the expense of durability. You can read more about unlogged tables here. The two tables are:

  1. http_request_queue: This table serves as a queue for requests waiting to be executed. Upon successful execution of a request, the corresponding data is removed from the queue.

    The SQL statement to create this table is:

    CREATE UNLOGGED TABLE
    net.http_request_queue (
    id bigintNOT NULL DEFAULT nextval('net.http_request_queue_id_seq'::regclass),
    method textNOT NULL,
    url textNOT NULL,
    headers jsonb,
    body bytea,
    timeout_milliseconds integerNOT NULL
    )
  2. _http_response: This table holds the responses of each executed request.

    The SQL statement to create this table is:

    CREATE UNLOGGED TABLE
    net._http_response (
    id bigintNULL,
    status_code integerNULL,
    content_type textNULL,
    headers jsonb NULL,
    content textNULL,
    timed_out booleanNULL,
    error_msg textNULL,
    created timestamp with time zoneNOT NULL DEFAULT now()
    )

When any of the three request functions (http_get, http_post, http_delete) are invoked, they create an entry in the net.http_request_queue table.

Once a response is received, it gets stored in the _http_response table. By monitoring this table, you can keep track of response statuses and messages.

Important

Inserting directly into the net.http_request_queue won't cause the worker to process requests, you must use the request functions. We do it this way to avoid polling the net.http_request_queue table, which would pollute pg_stat_statements and cause unnecesssary activity from the worker.

The extension employs C's libcurl library within a PostgreSQL background worker to manage HTTP requests. This background worker sleeps until it receives a signal from the request functions, which awakes it and prompts it to read the net.http_request_queue table and execute the requests on it.


Installation

Clone this repo and run

make && make install

To make the extension available to the database add on postgresql.conf:

shared_preload_libraries = 'pg_net'

By default, pg_net is available on the postgres database. To use pg_net on a different database, you can add the following on postgresql.conf:

pg_net.database_name = '<dbname>';

Using pg_net on multiple databases in a cluster is not yet supported.

To activate the extension in PostgreSQL, run the create extension command. The extension creates its own schema named net to avoid naming conflicts.

create extension pg_net;

Extension Configuration

The extension creates the following configurable variables:

  1. pg_net.batch_size(default: 200): An integer that limits the max number of rows that the extension will process from net.http_request_queue during each read
  2. pg_net.ttl(default: 6 hours): An interval that defines the max time a row in the net.http_response will live before being deleted. Note that this won't happen exactly after the TTL has passed. The worker will perform this deletion while its processing requests.
  3. pg_net.database_name(default: 'postgres'): A string that defines which database the extension is applied to
  4. pg_net.username(default: NULL): A string that defines which user will the background worker be connected with. If not set (NULL), it will assume the bootstrap user.

All these variables can be viewed with the following commands:

show pg_net.batch_size;
show pg_net.ttl;
show pg_net.database_name;
show pg_net.username;

You can change these by editing the postgresql.conf file (find it with SHOW config_file;) or with ALTER SYSTEM:

alter system set pg_net.ttl to '1 hour'
alter system set pg_net.batch_size to 500;

Then, you can reload the settings with:

select pg_reload_conf();

If you change the pg_net.database_name and pg_net.username configs, you'll need to restart the worker for them to apply. We provide a function that reloads the config with pg_reload_conf and restarts the worker in one go:

select net.worker_restart();

Note that doing ALTER SYSTEM requires SUPERUSER but on PostgreSQL >= 15, you can do:

grant alter system on parameter pg_net.ttl to <role>;
grant alter system on parameter pg_net.batch_size to <role>;

To allow regular users to update pg_net settings.

Requests API

GET requests

net.http_get function signature

net.http_get(
-- url for the request
url text,
-- key/value pairs to be url encoded and appended to the `url`
params jsonb default '{}'::jsonb,
-- key/values to be included in request headers
headers jsonb default '{}'::jsonb,
-- the maximum number of milliseconds the request may take before being cancelled
timeout_milliseconds int default 1000
)
-- request_id reference
returns bigint
strict
volatile
parallel safe
language plpgsql

Examples:

The following examples use the Postman Echo API.

Calling an API

SELECTnet.http_get (
'https://postman-echo.com/get?foo1=bar1&foo2=bar2'
) AS request_id;

NOTE: You can view the response with the following query:

SELECT*FROMnet._http_response;

Calling an API with URL encoded params

SELECTnet.http_get(
'https://postman-echo.com/get',
-- Equivalent to calling https://postman-echo.com/get?foo1=bar1&foo2=bar2&encoded=%21-- The "!" is url-encoded as %21'{"foo1": "bar1", "foo2": "bar2", "encoded": "!"}'::JSONB
) AS request_id;

Calling an API with an API-KEY

SELECTnet.http_get(
'https://postman-echo.com/get?foo1=bar1&foo2=bar2',
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id;

POST requests

net.http_post function signature

net.http_post(
-- url for the request
url text,
-- body of the POST request
body jsonb default '{}'::jsonb,
-- key/value pairs to be url encoded and appended to the `url`
params jsonb default '{}'::jsonb,
-- key/values to be included in request headers
headers jsonb default '{"Content-Type": "application/json"}'::jsonb,
-- the maximum number of milliseconds the request may take before being cancelled
timeout_milliseconds int default 1000
)
-- request_id reference
returns bigint
volatile
parallel safe
language plpgsql

Examples:

The following examples post to the Postman Echo API.

Sending data to an API

SELECTnet.http_post(
'https://postman-echo.com/post',
'{"key": "value", "key": 5}'::JSONB,
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id;

Sending single table row as a payload

NOTE: If multiple rows are sent using this method, each row will be sent as a separate request.

WITH selected_row AS (
SELECT*FROM target_table
LIMIT1
)
SELECTnet.http_post(
'https://postman-echo.com/post',
to_jsonb(selected_row.*),
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id
FROM selected_row;

Sending multiple table rows as a payload

WARNING: when sending multiple rows, be careful to limit your payload size.

WITH selected_rows AS (
SELECT-- Converts all the rows into a JSONB array
jsonb_agg(to_jsonb(target_table)) AS JSON_payload
FROM target_table
-- Generally good practice to LIMIT the max amount of rows
)
SELECTnet.http_post(
'https://postman-echo.com/post'::TEXT,
JSON_payload,
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id
FROM selected_rows;

DELETE requests

net.http_delete function signature

net.http_delete(
-- url for the request
url text,
-- key/value pairs to be url encoded and appended to the `url`
params jsonb default '{}'::jsonb,
-- key/values to be included in request headers
headers jsonb default '{}'::jsonb,
-- the maximum number of milliseconds the request may take before being cancelled
timeout_milliseconds int default 2000
)
-- request_id reference
returns bigint
strict
volatile
parallel safe
language plpgsql
security definer

Examples:

The following examples use the Dummy Rest API.

Sending a delete request to an API

SELECTnet.http_delete(
'https://dummy.restapiexample.com/api/v1/delete/2'
) AS request_id;

Sending a delete request with a row id as a query param

WITH selected_id AS (
SELECT
id
FROM target_table
LIMIT1-- if not limited, it will make a delete request for each returned row
)
SELECTnet.http_delete(
'https://dummy.restapiexample.com/api/v1/delete/'::TEXT,
format('{"id": "%s"}', id)::JSONB
) AS request_id
FROM selected_id;

Sending a delete request with a row id as a path param

WITH selected_id AS (
SELECT
id
FROM target_table
LIMIT1-- if not limited, it will make a delete request for each returned row
)
SELECTnet.http_delete(
'https://dummy.restapiexample.com/api/v1/delete/'|| id
) AS request_id
FROM selected_row

Practical Examples

Syncing data with an external data source using triggers

The following example comes from Typesense's Supabase Sync guide

-- Create the function to delete the record from TypesenseCREATE OR REPLACEFUNCTIONdelete_record()
RETURNS TRIGGER
LANGUAGE plpgSQL
AS $$
BEGINSELECTnet.http_delete(
url := format('<TYPESENSE URL>/collections/products/documents/%s', OLD.id),
headers :='{"X-Typesense-API-KEY": "<Typesense_API_KEY>"}'
)
RETURN OLD;
END $$;
-- Create the trigger that calls the function when a record is deleted from the products tableCREATETRIGGERdelete_products_trigger
AFTER DELETEONpublic.products
FOR EACH ROW
EXECUTE FUNCTION delete_products();

Calling a serverless function every minute with PG_CRON

The PG_CRON extension enables PostgreSQL to become its own cron server. With it you can schedule regular calls to activate serverless functions.

Useful links:

Example Cron job to call serverless function

SELECTcron.schedule(
'cron-job-name',
'* * * * *', -- Executes every minute (cron syntax)
$$
-- SQL querySELECTnet.http_get(
-- URL of Edge function
url:='https://<reference id>.functions.supabase.co/example',
headers:='{ "Content-Type": "application/json", "Authorization": "Bearer <TOKEN>" }'::JSONB
) as request_id;
$$
);

Retrying failed requests

Every request made is logged within the net._http_response table. To identify failed requests, you can execute a query on the table, filtering for requests where the status code is 500 or higher.

Finding failed requests

SELECT*FROMnet._http_responseWHERE status_code >=500;

While the net._http_response table logs each request, it doesn't store all the necessary information to retry failed requests. To facilitate this, we need to create a request tracking table and a wrapper function around the PG_NET request functions. This will help us store the required details for each request.

Creating a Request Tracker Table

CREATETABLErequest_tracker(
method TEXT,
url TEXT,
params JSONB,
body JSONB,
headers JSONB,
request_id BIGINT
)

Below is a function called request_wrapper, which wraps around the PG_NET request functions. This function records every request's details in the request_tracker table, facilitating future retries if needed.

Creating a Request Wrapper Function

CREATE OR REPLACEFUNCTIONrequest_wrapper(
method TEXT,
url TEXT,
params JSONB DEFAULT '{}'::JSONB,
body JSONB DEFAULT '{}'::JSONB,
headers JSONB DEFAULT '{}'::JSONB
)
RETURNS BIGINTAS $$
DECLARE
request_id BIGINT;
BEGIN
IF method ='DELETE' THEN
SELECTnet.http_delete(
url:=url,
params:=params,
headers:=headers
) INTO request_id;
ELSIF method ='POST' THEN
SELECTnet.http_post(
url:=url,
body:=body,
params:=params,
headers:=headers
) INTO request_id;
ELSIF method ='GET' THEN
SELECTnet.http_get(
url:=url,
params:=params,
headers:=headers
) INTO request_id;
ELSE
RAISE EXCEPTION 'Method must be DELETE, POST, or GET';
END IF;
INSERT INTO request_tracker (method, url, params, body, headers, request_id)
VALUES (method, url, params, body, headers, request_id);
RETURN request_id;
END;
$$
LANGUAGE plpgsql;

To retry a failed request recorded via the wrapper function, use the following query. This will select failed requests, retry them, and then remove the original request data from both the net._http_response and request_tracker tables.

Retrying failed requests

WITH retry_request AS (
SELECTrequest_tracker.method,
request_tracker.url,
request_tracker.params,
request_tracker.body,
request_tracker.headers,
request_tracker.request_idFROM request_tracker
INNER JOINnet._http_responseONnet._http_response.id =request_tracker.request_idWHEREnet._http_response.status_code >=500LIMIT3
),
retry AS (
SELECT
request_wrapper(retry_request.method, retry_request.url, retry_request.params, retry_request.body, retry_request.headers)
FROM retry_request
),
delete_http_response AS (
DELETEFROMnet._http_responseWHERE id IN (SELECT request_id FROM retry_request)
RETURNING *
)
DELETEFROM request_tracker
WHERE request_id IN (SELECT request_id FROM retry_request)
RETURNING *;

The above function can be called using cron jobs or manually to retry failed requests. It may also be beneficial to clean the request_tracker table in the process.

Contributing

Checkout the Contributing page to learn more about adding to the project.

About

A PostgreSQL extension that enables asynchronous (non-blocking) HTTP/HTTPS requests with SQL

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

368 stars

Watchers

27 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

PG_NET

A PostgreSQL extension that enables asynchronous (non-blocking) HTTP/HTTPS requests with SQL.

Requires libcurl >= 7.83. Compatible with PostgreSQL > = 12.

PostgreSQL versionLicenseCoverage StatusTests


Contents


Introduction

The PG_NET extension enables PostgreSQL to make asynchronous HTTP/HTTPS requests in SQL. It eliminates the need for servers to continuously poll for database changes and instead allows the database to proactively notify external resources about significant events. It seamlessly integrates with triggers, cron jobs (e.g., PG_CRON), and procedures, unlocking numerous possibilities. Notably, PG_NET powers Supabase's Webhook functionality, highlighting its robustness and reliability.

Common use cases for the PG_NET extension include:

  • Calling external APIs
  • Syncing data with outside resources
  • Calling a serverless function when an event, such as an insert, occurred

However, it is important to note that the extension has a few limitations. Currently, it only supports three types of asynchronous requests:

  • async http GET requests
  • async http POST requests with a JSON payload
  • async http DELETE requests

Ultimately, though, PG_NET offers developers more flexibility in how they monitor and connect their database with external resources.


Technical Explanation

The extension introduces a new net schema, which contains two unlogged tables, a type of table in PostgreSQL that offers performance improvements at the expense of durability. You can read more about unlogged tables here. The two tables are:

  1. http_request_queue: This table serves as a queue for requests waiting to be executed. Upon successful execution of a request, the corresponding data is removed from the queue.

    The SQL statement to create this table is:

    CREATE UNLOGGED TABLE
    net.http_request_queue (
    id bigintNOT NULL DEFAULT nextval('net.http_request_queue_id_seq'::regclass),
    method textNOT NULL,
    url textNOT NULL,
    headers jsonb,
    body bytea,
    timeout_milliseconds integerNOT NULL
    )
  2. _http_response: This table holds the responses of each executed request.

    The SQL statement to create this table is:

    CREATE UNLOGGED TABLE
    net._http_response (
    id bigintNULL,
    status_code integerNULL,
    content_type textNULL,
    headers jsonb NULL,
    content textNULL,
    timed_out booleanNULL,
    error_msg textNULL,
    created timestamp with time zoneNOT NULL DEFAULT now()
    )

When any of the three request functions (http_get, http_post, http_delete) are invoked, they create an entry in the net.http_request_queue table.

Once a response is received, it gets stored in the _http_response table. By monitoring this table, you can keep track of response statuses and messages.

Important

Inserting directly into the net.http_request_queue won't cause the worker to process requests, you must use the request functions. We do it this way to avoid polling the net.http_request_queue table, which would pollute pg_stat_statements and cause unnecesssary activity from the worker.

The extension employs C's libcurl library within a PostgreSQL background worker to manage HTTP requests. This background worker sleeps until it receives a signal from the request functions, which awakes it and prompts it to read the net.http_request_queue table and execute the requests on it.


Installation

Clone this repo and run

make && make install

To make the extension available to the database add on postgresql.conf:

shared_preload_libraries = 'pg_net'

By default, pg_net is available on the postgres database. To use pg_net on a different database, you can add the following on postgresql.conf:

pg_net.database_name = '<dbname>';

Using pg_net on multiple databases in a cluster is not yet supported.

To activate the extension in PostgreSQL, run the create extension command. The extension creates its own schema named net to avoid naming conflicts.

create extension pg_net;

Extension Configuration

The extension creates the following configurable variables:

  1. pg_net.batch_size(default: 200): An integer that limits the max number of rows that the extension will process from net.http_request_queue during each read
  2. pg_net.ttl(default: 6 hours): An interval that defines the max time a row in the net.http_response will live before being deleted. Note that this won't happen exactly after the TTL has passed. The worker will perform this deletion while its processing requests.
  3. pg_net.database_name(default: 'postgres'): A string that defines which database the extension is applied to
  4. pg_net.username(default: NULL): A string that defines which user will the background worker be connected with. If not set (NULL), it will assume the bootstrap user.

All these variables can be viewed with the following commands:

show pg_net.batch_size;
show pg_net.ttl;
show pg_net.database_name;
show pg_net.username;

You can change these by editing the postgresql.conf file (find it with SHOW config_file;) or with ALTER SYSTEM:

alter system set pg_net.ttl to '1 hour'
alter system set pg_net.batch_size to 500;

Then, you can reload the settings with:

select pg_reload_conf();

If you change the pg_net.database_name and pg_net.username configs, you'll need to restart the worker for them to apply. We provide a function that reloads the config with pg_reload_conf and restarts the worker in one go:

select net.worker_restart();

Note that doing ALTER SYSTEM requires SUPERUSER but on PostgreSQL >= 15, you can do:

grant alter system on parameter pg_net.ttl to <role>;
grant alter system on parameter pg_net.batch_size to <role>;

To allow regular users to update pg_net settings.

Requests API

GET requests

net.http_get function signature

net.http_get(
-- url for the request
url text,
-- key/value pairs to be url encoded and appended to the `url`
params jsonb default '{}'::jsonb,
-- key/values to be included in request headers
headers jsonb default '{}'::jsonb,
-- the maximum number of milliseconds the request may take before being cancelled
timeout_milliseconds int default 1000
)
-- request_id reference
returns bigint
strict
volatile
parallel safe
language plpgsql

Examples:

The following examples use the Postman Echo API.

Calling an API

SELECTnet.http_get (
'https://postman-echo.com/get?foo1=bar1&foo2=bar2'
) AS request_id;

NOTE: You can view the response with the following query:

SELECT*FROMnet._http_response;

Calling an API with URL encoded params

SELECTnet.http_get(
'https://postman-echo.com/get',
-- Equivalent to calling https://postman-echo.com/get?foo1=bar1&foo2=bar2&encoded=%21-- The "!" is url-encoded as %21'{"foo1": "bar1", "foo2": "bar2", "encoded": "!"}'::JSONB
) AS request_id;

Calling an API with an API-KEY

SELECTnet.http_get(
'https://postman-echo.com/get?foo1=bar1&foo2=bar2',
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id;

POST requests

net.http_post function signature

net.http_post(
-- url for the request
url text,
-- body of the POST request
body jsonb default '{}'::jsonb,
-- key/value pairs to be url encoded and appended to the `url`
params jsonb default '{}'::jsonb,
-- key/values to be included in request headers
headers jsonb default '{"Content-Type": "application/json"}'::jsonb,
-- the maximum number of milliseconds the request may take before being cancelled
timeout_milliseconds int default 1000
)
-- request_id reference
returns bigint
volatile
parallel safe
language plpgsql

Examples:

The following examples post to the Postman Echo API.

Sending data to an API

SELECTnet.http_post(
'https://postman-echo.com/post',
'{"key": "value", "key": 5}'::JSONB,
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id;

Sending single table row as a payload

NOTE: If multiple rows are sent using this method, each row will be sent as a separate request.

WITH selected_row AS (
SELECT*FROM target_table
LIMIT1
)
SELECTnet.http_post(
'https://postman-echo.com/post',
to_jsonb(selected_row.*),
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id
FROM selected_row;

Sending multiple table rows as a payload

WARNING: when sending multiple rows, be careful to limit your payload size.

WITH selected_rows AS (
SELECT-- Converts all the rows into a JSONB array
jsonb_agg(to_jsonb(target_table)) AS JSON_payload
FROM target_table
-- Generally good practice to LIMIT the max amount of rows
)
SELECTnet.http_post(
'https://postman-echo.com/post'::TEXT,
JSON_payload,
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id
FROM selected_rows;

DELETE requests

net.http_delete function signature

net.http_delete(
-- url for the request
url text,
-- key/value pairs to be url encoded and appended to the `url`
params jsonb default '{}'::jsonb,
-- key/values to be included in request headers
headers jsonb default '{}'::jsonb,
-- the maximum number of milliseconds the request may take before being cancelled
timeout_milliseconds int default 2000
)
-- request_id reference
returns bigint
strict
volatile
parallel safe
language plpgsql
security definer

Examples:

The following examples use the Dummy Rest API.

Sending a delete request to an API

SELECTnet.http_delete(
'https://dummy.restapiexample.com/api/v1/delete/2'
) AS request_id;

Sending a delete request with a row id as a query param

WITH selected_id AS (
SELECT
id
FROM target_table
LIMIT1-- if not limited, it will make a delete request for each returned row
)
SELECTnet.http_delete(
'https://dummy.restapiexample.com/api/v1/delete/'::TEXT,
format('{"id": "%s"}', id)::JSONB
) AS request_id
FROM selected_id;

Sending a delete request with a row id as a path param

WITH selected_id AS (
SELECT
id
FROM target_table
LIMIT1-- if not limited, it will make a delete request for each returned row
)
SELECTnet.http_delete(
'https://dummy.restapiexample.com/api/v1/delete/'|| id
) AS request_id
FROM selected_row

Practical Examples

Syncing data with an external data source using triggers

The following example comes from Typesense's Supabase Sync guide

-- Create the function to delete the record from TypesenseCREATE OR REPLACEFUNCTIONdelete_record()
RETURNS TRIGGER
LANGUAGE plpgSQL
AS $$
BEGINSELECTnet.http_delete(
url := format('<TYPESENSE URL>/collections/products/documents/%s', OLD.id),
headers :='{"X-Typesense-API-KEY": "<Typesense_API_KEY>"}'
)
RETURN OLD;
END $$;
-- Create the trigger that calls the function when a record is deleted from the products tableCREATETRIGGERdelete_products_trigger
AFTER DELETEONpublic.products
FOR EACH ROW
EXECUTE FUNCTION delete_products();

Calling a serverless function every minute with PG_CRON

The PG_CRON extension enables PostgreSQL to become its own cron server. With it you can schedule regular calls to activate serverless functions.

Useful links:

Example Cron job to call serverless function

SELECTcron.schedule(
'cron-job-name',
'* * * * *', -- Executes every minute (cron syntax)
$$
-- SQL querySELECTnet.http_get(
-- URL of Edge function
url:='https://<reference id>.functions.supabase.co/example',
headers:='{ "Content-Type": "application/json", "Authorization": "Bearer <TOKEN>" }'::JSONB
) as request_id;
$$
);

Retrying failed requests

Every request made is logged within the net._http_response table. To identify failed requests, you can execute a query on the table, filtering for requests where the status code is 500 or higher.

Finding failed requests

SELECT*FROMnet._http_responseWHERE status_code >=500;

While the net._http_response table logs each request, it doesn't store all the necessary information to retry failed requests. To facilitate this, we need to create a request tracking table and a wrapper function around the PG_NET request functions. This will help us store the required details for each request.

Creating a Request Tracker Table

CREATETABLErequest_tracker(
method TEXT,
url TEXT,
params JSONB,
body JSONB,
headers JSONB,
request_id BIGINT
)

Below is a function called request_wrapper, which wraps around the PG_NET request functions. This function records every request's details in the request_tracker table, facilitating future retries if needed.

Creating a Request Wrapper Function

CREATE OR REPLACEFUNCTIONrequest_wrapper(
method TEXT,
url TEXT,
params JSONB DEFAULT '{}'::JSONB,
body JSONB DEFAULT '{}'::JSONB,
headers JSONB DEFAULT '{}'::JSONB
)
RETURNS BIGINTAS $$
DECLARE
request_id BIGINT;
BEGIN
IF method ='DELETE' THEN
SELECTnet.http_delete(
url:=url,
params:=params,
headers:=headers
) INTO request_id;
ELSIF method ='POST' THEN
SELECTnet.http_post(
url:=url,
body:=body,
params:=params,
headers:=headers
) INTO request_id;
ELSIF method ='GET' THEN
SELECTnet.http_get(
url:=url,
params:=params,
headers:=headers
) INTO request_id;
ELSE
RAISE EXCEPTION 'Method must be DELETE, POST, or GET';
END IF;
INSERT INTO request_tracker (method, url, params, body, headers, request_id)
VALUES (method, url, params, body, headers, request_id);
RETURN request_id;
END;
$$
LANGUAGE plpgsql;

To retry a failed request recorded via the wrapper function, use the following query. This will select failed requests, retry them, and then remove the original request data from both the net._http_response and request_tracker tables.

Retrying failed requests

WITH retry_request AS (
SELECTrequest_tracker.method,
request_tracker.url,
request_tracker.params,
request_tracker.body,
request_tracker.headers,
request_tracker.request_idFROM request_tracker
INNER JOINnet._http_responseONnet._http_response.id =request_tracker.request_idWHEREnet._http_response.status_code >=500LIMIT3
),
retry AS (
SELECT
request_wrapper(retry_request.method, retry_request.url, retry_request.params, retry_request.body, retry_request.headers)
FROM retry_request
),
delete_http_response AS (
DELETEFROMnet._http_responseWHERE id IN (SELECT request_id FROM retry_request)
RETURNING *
)
DELETEFROM request_tracker
WHERE request_id IN (SELECT request_id FROM retry_request)
RETURNING *;

The above function can be called using cron jobs or manually to retry failed requests. It may also be beneficial to clean the request_tracker table in the process.

Contributing

Checkout the Contributing page to learn more about adding to the project.

About

A PostgreSQL extension that enables asynchronous (non-blocking) HTTP/HTTPS requests with SQL

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

368 stars

Watchers

27 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

PG_NET

A PostgreSQL extension that enables asynchronous (non-blocking) HTTP/HTTPS requests with SQL.

Requires libcurl >= 7.83. Compatible with PostgreSQL > = 12.

PostgreSQL versionLicenseCoverage StatusTests


Contents


Introduction

The PG_NET extension enables PostgreSQL to make asynchronous HTTP/HTTPS requests in SQL. It eliminates the need for servers to continuously poll for database changes and instead allows the database to proactively notify external resources about significant events. It seamlessly integrates with triggers, cron jobs (e.g., PG_CRON), and procedures, unlocking numerous possibilities. Notably, PG_NET powers Supabase's Webhook functionality, highlighting its robustness and reliability.

Common use cases for the PG_NET extension include:

  • Calling external APIs
  • Syncing data with outside resources
  • Calling a serverless function when an event, such as an insert, occurred

However, it is important to note that the extension has a few limitations. Currently, it only supports three types of asynchronous requests:

  • async http GET requests
  • async http POST requests with a JSON payload
  • async http DELETE requests

Ultimately, though, PG_NET offers developers more flexibility in how they monitor and connect their database with external resources.


Technical Explanation

The extension introduces a new net schema, which contains two unlogged tables, a type of table in PostgreSQL that offers performance improvements at the expense of durability. You can read more about unlogged tables here. The two tables are:

  1. http_request_queue: This table serves as a queue for requests waiting to be executed. Upon successful execution of a request, the corresponding data is removed from the queue.

    The SQL statement to create this table is:

    CREATE UNLOGGED TABLE
    net.http_request_queue (
    id bigintNOT NULL DEFAULT nextval('net.http_request_queue_id_seq'::regclass),
    method textNOT NULL,
    url textNOT NULL,
    headers jsonb,
    body bytea,
    timeout_milliseconds integerNOT NULL
    )
  2. _http_response: This table holds the responses of each executed request.

    The SQL statement to create this table is:

    CREATE UNLOGGED TABLE
    net._http_response (
    id bigintNULL,
    status_code integerNULL,
    content_type textNULL,
    headers jsonb NULL,
    content textNULL,
    timed_out booleanNULL,
    error_msg textNULL,
    created timestamp with time zoneNOT NULL DEFAULT now()
    )

When any of the three request functions (http_get, http_post, http_delete) are invoked, they create an entry in the net.http_request_queue table.

Once a response is received, it gets stored in the _http_response table. By monitoring this table, you can keep track of response statuses and messages.

Important

Inserting directly into the net.http_request_queue won't cause the worker to process requests, you must use the request functions. We do it this way to avoid polling the net.http_request_queue table, which would pollute pg_stat_statements and cause unnecesssary activity from the worker.

The extension employs C's libcurl library within a PostgreSQL background worker to manage HTTP requests. This background worker sleeps until it receives a signal from the request functions, which awakes it and prompts it to read the net.http_request_queue table and execute the requests on it.


Installation

Clone this repo and run

make && make install

To make the extension available to the database add on postgresql.conf:

shared_preload_libraries = 'pg_net'

By default, pg_net is available on the postgres database. To use pg_net on a different database, you can add the following on postgresql.conf:

pg_net.database_name = '<dbname>';

Using pg_net on multiple databases in a cluster is not yet supported.

To activate the extension in PostgreSQL, run the create extension command. The extension creates its own schema named net to avoid naming conflicts.

create extension pg_net;

Extension Configuration

The extension creates the following configurable variables:

  1. pg_net.batch_size(default: 200): An integer that limits the max number of rows that the extension will process from net.http_request_queue during each read
  2. pg_net.ttl(default: 6 hours): An interval that defines the max time a row in the net.http_response will live before being deleted. Note that this won't happen exactly after the TTL has passed. The worker will perform this deletion while its processing requests.
  3. pg_net.database_name(default: 'postgres'): A string that defines which database the extension is applied to
  4. pg_net.username(default: NULL): A string that defines which user will the background worker be connected with. If not set (NULL), it will assume the bootstrap user.

All these variables can be viewed with the following commands:

show pg_net.batch_size;
show pg_net.ttl;
show pg_net.database_name;
show pg_net.username;

You can change these by editing the postgresql.conf file (find it with SHOW config_file;) or with ALTER SYSTEM:

alter system set pg_net.ttl to '1 hour'
alter system set pg_net.batch_size to 500;

Then, you can reload the settings with:

select pg_reload_conf();

If you change the pg_net.database_name and pg_net.username configs, you'll need to restart the worker for them to apply. We provide a function that reloads the config with pg_reload_conf and restarts the worker in one go:

select net.worker_restart();

Note that doing ALTER SYSTEM requires SUPERUSER but on PostgreSQL >= 15, you can do:

grant alter system on parameter pg_net.ttl to <role>;
grant alter system on parameter pg_net.batch_size to <role>;

To allow regular users to update pg_net settings.

Requests API

GET requests

net.http_get function signature

net.http_get(
-- url for the request
url text,
-- key/value pairs to be url encoded and appended to the `url`
params jsonb default '{}'::jsonb,
-- key/values to be included in request headers
headers jsonb default '{}'::jsonb,
-- the maximum number of milliseconds the request may take before being cancelled
timeout_milliseconds int default 1000
)
-- request_id reference
returns bigint
strict
volatile
parallel safe
language plpgsql

Examples:

The following examples use the Postman Echo API.

Calling an API

SELECTnet.http_get (
'https://postman-echo.com/get?foo1=bar1&foo2=bar2'
) AS request_id;

NOTE: You can view the response with the following query:

SELECT*FROMnet._http_response;

Calling an API with URL encoded params

SELECTnet.http_get(
'https://postman-echo.com/get',
-- Equivalent to calling https://postman-echo.com/get?foo1=bar1&foo2=bar2&encoded=%21-- The "!" is url-encoded as %21'{"foo1": "bar1", "foo2": "bar2", "encoded": "!"}'::JSONB
) AS request_id;

Calling an API with an API-KEY

SELECTnet.http_get(
'https://postman-echo.com/get?foo1=bar1&foo2=bar2',
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id;

POST requests

net.http_post function signature

net.http_post(
-- url for the request
url text,
-- body of the POST request
body jsonb default '{}'::jsonb,
-- key/value pairs to be url encoded and appended to the `url`
params jsonb default '{}'::jsonb,
-- key/values to be included in request headers
headers jsonb default '{"Content-Type": "application/json"}'::jsonb,
-- the maximum number of milliseconds the request may take before being cancelled
timeout_milliseconds int default 1000
)
-- request_id reference
returns bigint
volatile
parallel safe
language plpgsql

Examples:

The following examples post to the Postman Echo API.

Sending data to an API

SELECTnet.http_post(
'https://postman-echo.com/post',
'{"key": "value", "key": 5}'::JSONB,
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id;

Sending single table row as a payload

NOTE: If multiple rows are sent using this method, each row will be sent as a separate request.

WITH selected_row AS (
SELECT*FROM target_table
LIMIT1
)
SELECTnet.http_post(
'https://postman-echo.com/post',
to_jsonb(selected_row.*),
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id
FROM selected_row;

Sending multiple table rows as a payload

WARNING: when sending multiple rows, be careful to limit your payload size.

WITH selected_rows AS (
SELECT-- Converts all the rows into a JSONB array
jsonb_agg(to_jsonb(target_table)) AS JSON_payload
FROM target_table
-- Generally good practice to LIMIT the max amount of rows
)
SELECTnet.http_post(
'https://postman-echo.com/post'::TEXT,
JSON_payload,
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id
FROM selected_rows;

DELETE requests

net.http_delete function signature

net.http_delete(
-- url for the request
url text,
-- key/value pairs to be url encoded and appended to the `url`
params jsonb default '{}'::jsonb,
-- key/values to be included in request headers
headers jsonb default '{}'::jsonb,
-- the maximum number of milliseconds the request may take before being cancelled
timeout_milliseconds int default 2000
)
-- request_id reference
returns bigint
strict
volatile
parallel safe
language plpgsql
security definer

Examples:

The following examples use the Dummy Rest API.

Sending a delete request to an API

SELECTnet.http_delete(
'https://dummy.restapiexample.com/api/v1/delete/2'
) AS request_id;

Sending a delete request with a row id as a query param

WITH selected_id AS (
SELECT
id
FROM target_table
LIMIT1-- if not limited, it will make a delete request for each returned row
)
SELECTnet.http_delete(
'https://dummy.restapiexample.com/api/v1/delete/'::TEXT,
format('{"id": "%s"}', id)::JSONB
) AS request_id
FROM selected_id;

Sending a delete request with a row id as a path param

WITH selected_id AS (
SELECT
id
FROM target_table
LIMIT1-- if not limited, it will make a delete request for each returned row
)
SELECTnet.http_delete(
'https://dummy.restapiexample.com/api/v1/delete/'|| id
) AS request_id
FROM selected_row

Practical Examples

Syncing data with an external data source using triggers

The following example comes from Typesense's Supabase Sync guide

-- Create the function to delete the record from TypesenseCREATE OR REPLACEFUNCTIONdelete_record()
RETURNS TRIGGER
LANGUAGE plpgSQL
AS $$
BEGINSELECTnet.http_delete(
url := format('<TYPESENSE URL>/collections/products/documents/%s', OLD.id),
headers :='{"X-Typesense-API-KEY": "<Typesense_API_KEY>"}'
)
RETURN OLD;
END $$;
-- Create the trigger that calls the function when a record is deleted from the products tableCREATETRIGGERdelete_products_trigger
AFTER DELETEONpublic.products
FOR EACH ROW
EXECUTE FUNCTION delete_products();

Calling a serverless function every minute with PG_CRON

The PG_CRON extension enables PostgreSQL to become its own cron server. With it you can schedule regular calls to activate serverless functions.

Useful links:

Example Cron job to call serverless function

SELECTcron.schedule(
'cron-job-name',
'* * * * *', -- Executes every minute (cron syntax)
$$
-- SQL querySELECTnet.http_get(
-- URL of Edge function
url:='https://<reference id>.functions.supabase.co/example',
headers:='{ "Content-Type": "application/json", "Authorization": "Bearer <TOKEN>" }'::JSONB
) as request_id;
$$
);

Retrying failed requests

Every request made is logged within the net._http_response table. To identify failed requests, you can execute a query on the table, filtering for requests where the status code is 500 or higher.

Finding failed requests

SELECT*FROMnet._http_responseWHERE status_code >=500;

While the net._http_response table logs each request, it doesn't store all the necessary information to retry failed requests. To facilitate this, we need to create a request tracking table and a wrapper function around the PG_NET request functions. This will help us store the required details for each request.

Creating a Request Tracker Table

CREATETABLErequest_tracker(
method TEXT,
url TEXT,
params JSONB,
body JSONB,
headers JSONB,
request_id BIGINT
)

Below is a function called request_wrapper, which wraps around the PG_NET request functions. This function records every request's details in the request_tracker table, facilitating future retries if needed.

Creating a Request Wrapper Function

CREATE OR REPLACEFUNCTIONrequest_wrapper(
method TEXT,
url TEXT,
params JSONB DEFAULT '{}'::JSONB,
body JSONB DEFAULT '{}'::JSONB,
headers JSONB DEFAULT '{}'::JSONB
)
RETURNS BIGINTAS $$
DECLARE
request_id BIGINT;
BEGIN
IF method ='DELETE' THEN
SELECTnet.http_delete(
url:=url,
params:=params,
headers:=headers
) INTO request_id;
ELSIF method ='POST' THEN
SELECTnet.http_post(
url:=url,
body:=body,
params:=params,
headers:=headers
) INTO request_id;
ELSIF method ='GET' THEN
SELECTnet.http_get(
url:=url,
params:=params,
headers:=headers
) INTO request_id;
ELSE
RAISE EXCEPTION 'Method must be DELETE, POST, or GET';
END IF;
INSERT INTO request_tracker (method, url, params, body, headers, request_id)
VALUES (method, url, params, body, headers, request_id);
RETURN request_id;
END;
$$
LANGUAGE plpgsql;

To retry a failed request recorded via the wrapper function, use the following query. This will select failed requests, retry them, and then remove the original request data from both the net._http_response and request_tracker tables.

Retrying failed requests

WITH retry_request AS (
SELECTrequest_tracker.method,
request_tracker.url,
request_tracker.params,
request_tracker.body,
request_tracker.headers,
request_tracker.request_idFROM request_tracker
INNER JOINnet._http_responseONnet._http_response.id =request_tracker.request_idWHEREnet._http_response.status_code >=500LIMIT3
),
retry AS (
SELECT
request_wrapper(retry_request.method, retry_request.url, retry_request.params, retry_request.body, retry_request.headers)
FROM retry_request
),
delete_http_response AS (
DELETEFROMnet._http_responseWHERE id IN (SELECT request_id FROM retry_request)
RETURNING *
)
DELETEFROM request_tracker
WHERE request_id IN (SELECT request_id FROM retry_request)
RETURNING *;

The above function can be called using cron jobs or manually to retry failed requests. It may also be beneficial to clean the request_tracker table in the process.

Contributing

Checkout the Contributing page to learn more about adding to the project.

About

A PostgreSQL extension that enables asynchronous (non-blocking) HTTP/HTTPS requests with SQL

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

368 stars

Watchers

27 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

PG_NET

A PostgreSQL extension that enables asynchronous (non-blocking) HTTP/HTTPS requests with SQL.

Requires libcurl >= 7.83. Compatible with PostgreSQL > = 12.

PostgreSQL versionLicenseCoverage StatusTests


Contents


Introduction

The PG_NET extension enables PostgreSQL to make asynchronous HTTP/HTTPS requests in SQL. It eliminates the need for servers to continuously poll for database changes and instead allows the database to proactively notify external resources about significant events. It seamlessly integrates with triggers, cron jobs (e.g., PG_CRON), and procedures, unlocking numerous possibilities. Notably, PG_NET powers Supabase's Webhook functionality, highlighting its robustness and reliability.

Common use cases for the PG_NET extension include:

  • Calling external APIs
  • Syncing data with outside resources
  • Calling a serverless function when an event, such as an insert, occurred

However, it is important to note that the extension has a few limitations. Currently, it only supports three types of asynchronous requests:

  • async http GET requests
  • async http POST requests with a JSON payload
  • async http DELETE requests

Ultimately, though, PG_NET offers developers more flexibility in how they monitor and connect their database with external resources.


Technical Explanation

The extension introduces a new net schema, which contains two unlogged tables, a type of table in PostgreSQL that offers performance improvements at the expense of durability. You can read more about unlogged tables here. The two tables are:

  1. http_request_queue: This table serves as a queue for requests waiting to be executed. Upon successful execution of a request, the corresponding data is removed from the queue.

    The SQL statement to create this table is:

    CREATE UNLOGGED TABLE
    net.http_request_queue (
    id bigintNOT NULL DEFAULT nextval('net.http_request_queue_id_seq'::regclass),
    method textNOT NULL,
    url textNOT NULL,
    headers jsonb,
    body bytea,
    timeout_milliseconds integerNOT NULL
    )
  2. _http_response: This table holds the responses of each executed request.

    The SQL statement to create this table is:

    CREATE UNLOGGED TABLE
    net._http_response (
    id bigintNULL,
    status_code integerNULL,
    content_type textNULL,
    headers jsonb NULL,
    content textNULL,
    timed_out booleanNULL,
    error_msg textNULL,
    created timestamp with time zoneNOT NULL DEFAULT now()
    )

When any of the three request functions (http_get, http_post, http_delete) are invoked, they create an entry in the net.http_request_queue table.

Once a response is received, it gets stored in the _http_response table. By monitoring this table, you can keep track of response statuses and messages.

Important

Inserting directly into the net.http_request_queue won't cause the worker to process requests, you must use the request functions. We do it this way to avoid polling the net.http_request_queue table, which would pollute pg_stat_statements and cause unnecesssary activity from the worker.

The extension employs C's libcurl library within a PostgreSQL background worker to manage HTTP requests. This background worker sleeps until it receives a signal from the request functions, which awakes it and prompts it to read the net.http_request_queue table and execute the requests on it.


Installation

Clone this repo and run

make && make install

To make the extension available to the database add on postgresql.conf:

shared_preload_libraries = 'pg_net'

By default, pg_net is available on the postgres database. To use pg_net on a different database, you can add the following on postgresql.conf:

pg_net.database_name = '<dbname>';

Using pg_net on multiple databases in a cluster is not yet supported.

To activate the extension in PostgreSQL, run the create extension command. The extension creates its own schema named net to avoid naming conflicts.

create extension pg_net;

Extension Configuration

The extension creates the following configurable variables:

  1. pg_net.batch_size(default: 200): An integer that limits the max number of rows that the extension will process from net.http_request_queue during each read
  2. pg_net.ttl(default: 6 hours): An interval that defines the max time a row in the net.http_response will live before being deleted. Note that this won't happen exactly after the TTL has passed. The worker will perform this deletion while its processing requests.
  3. pg_net.database_name(default: 'postgres'): A string that defines which database the extension is applied to
  4. pg_net.username(default: NULL): A string that defines which user will the background worker be connected with. If not set (NULL), it will assume the bootstrap user.

All these variables can be viewed with the following commands:

show pg_net.batch_size;
show pg_net.ttl;
show pg_net.database_name;
show pg_net.username;

You can change these by editing the postgresql.conf file (find it with SHOW config_file;) or with ALTER SYSTEM:

alter system set pg_net.ttl to '1 hour'
alter system set pg_net.batch_size to 500;

Then, you can reload the settings with:

select pg_reload_conf();

If you change the pg_net.database_name and pg_net.username configs, you'll need to restart the worker for them to apply. We provide a function that reloads the config with pg_reload_conf and restarts the worker in one go:

select net.worker_restart();

Note that doing ALTER SYSTEM requires SUPERUSER but on PostgreSQL >= 15, you can do:

grant alter system on parameter pg_net.ttl to <role>;
grant alter system on parameter pg_net.batch_size to <role>;

To allow regular users to update pg_net settings.

Requests API

GET requests

net.http_get function signature

net.http_get(
-- url for the request
url text,
-- key/value pairs to be url encoded and appended to the `url`
params jsonb default '{}'::jsonb,
-- key/values to be included in request headers
headers jsonb default '{}'::jsonb,
-- the maximum number of milliseconds the request may take before being cancelled
timeout_milliseconds int default 1000
)
-- request_id reference
returns bigint
strict
volatile
parallel safe
language plpgsql

Examples:

The following examples use the Postman Echo API.

Calling an API

SELECTnet.http_get (
'https://postman-echo.com/get?foo1=bar1&foo2=bar2'
) AS request_id;

NOTE: You can view the response with the following query:

SELECT*FROMnet._http_response;

Calling an API with URL encoded params

SELECTnet.http_get(
'https://postman-echo.com/get',
-- Equivalent to calling https://postman-echo.com/get?foo1=bar1&foo2=bar2&encoded=%21-- The "!" is url-encoded as %21'{"foo1": "bar1", "foo2": "bar2", "encoded": "!"}'::JSONB
) AS request_id;

Calling an API with an API-KEY

SELECTnet.http_get(
'https://postman-echo.com/get?foo1=bar1&foo2=bar2',
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id;

POST requests

net.http_post function signature

net.http_post(
-- url for the request
url text,
-- body of the POST request
body jsonb default '{}'::jsonb,
-- key/value pairs to be url encoded and appended to the `url`
params jsonb default '{}'::jsonb,
-- key/values to be included in request headers
headers jsonb default '{"Content-Type": "application/json"}'::jsonb,
-- the maximum number of milliseconds the request may take before being cancelled
timeout_milliseconds int default 1000
)
-- request_id reference
returns bigint
volatile
parallel safe
language plpgsql

Examples:

The following examples post to the Postman Echo API.

Sending data to an API

SELECTnet.http_post(
'https://postman-echo.com/post',
'{"key": "value", "key": 5}'::JSONB,
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id;

Sending single table row as a payload

NOTE: If multiple rows are sent using this method, each row will be sent as a separate request.

WITH selected_row AS (
SELECT*FROM target_table
LIMIT1
)
SELECTnet.http_post(
'https://postman-echo.com/post',
to_jsonb(selected_row.*),
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id
FROM selected_row;

Sending multiple table rows as a payload

WARNING: when sending multiple rows, be careful to limit your payload size.

WITH selected_rows AS (
SELECT-- Converts all the rows into a JSONB array
jsonb_agg(to_jsonb(target_table)) AS JSON_payload
FROM target_table
-- Generally good practice to LIMIT the max amount of rows
)
SELECTnet.http_post(
'https://postman-echo.com/post'::TEXT,
JSON_payload,
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id
FROM selected_rows;

DELETE requests

net.http_delete function signature

net.http_delete(
-- url for the request
url text,
-- key/value pairs to be url encoded and appended to the `url`
params jsonb default '{}'::jsonb,
-- key/values to be included in request headers
headers jsonb default '{}'::jsonb,
-- the maximum number of milliseconds the request may take before being cancelled
timeout_milliseconds int default 2000
)
-- request_id reference
returns bigint
strict
volatile
parallel safe
language plpgsql
security definer

Examples:

The following examples use the Dummy Rest API.

Sending a delete request to an API

SELECTnet.http_delete(
'https://dummy.restapiexample.com/api/v1/delete/2'
) AS request_id;

Sending a delete request with a row id as a query param

WITH selected_id AS (
SELECT
id
FROM target_table
LIMIT1-- if not limited, it will make a delete request for each returned row
)
SELECTnet.http_delete(
'https://dummy.restapiexample.com/api/v1/delete/'::TEXT,
format('{"id": "%s"}', id)::JSONB
) AS request_id
FROM selected_id;

Sending a delete request with a row id as a path param

WITH selected_id AS (
SELECT
id
FROM target_table
LIMIT1-- if not limited, it will make a delete request for each returned row
)
SELECTnet.http_delete(
'https://dummy.restapiexample.com/api/v1/delete/'|| id
) AS request_id
FROM selected_row

Practical Examples

Syncing data with an external data source using triggers

The following example comes from Typesense's Supabase Sync guide

-- Create the function to delete the record from TypesenseCREATE OR REPLACEFUNCTIONdelete_record()
RETURNS TRIGGER
LANGUAGE plpgSQL
AS $$
BEGINSELECTnet.http_delete(
url := format('<TYPESENSE URL>/collections/products/documents/%s', OLD.id),
headers :='{"X-Typesense-API-KEY": "<Typesense_API_KEY>"}'
)
RETURN OLD;
END $$;
-- Create the trigger that calls the function when a record is deleted from the products tableCREATETRIGGERdelete_products_trigger
AFTER DELETEONpublic.products
FOR EACH ROW
EXECUTE FUNCTION delete_products();

Calling a serverless function every minute with PG_CRON

The PG_CRON extension enables PostgreSQL to become its own cron server. With it you can schedule regular calls to activate serverless functions.

Useful links:

Example Cron job to call serverless function

SELECTcron.schedule(
'cron-job-name',
'* * * * *', -- Executes every minute (cron syntax)
$$
-- SQL querySELECTnet.http_get(
-- URL of Edge function
url:='https://<reference id>.functions.supabase.co/example',
headers:='{ "Content-Type": "application/json", "Authorization": "Bearer <TOKEN>" }'::JSONB
) as request_id;
$$
);

Retrying failed requests

Every request made is logged within the net._http_response table. To identify failed requests, you can execute a query on the table, filtering for requests where the status code is 500 or higher.

Finding failed requests

SELECT*FROMnet._http_responseWHERE status_code >=500;

While the net._http_response table logs each request, it doesn't store all the necessary information to retry failed requests. To facilitate this, we need to create a request tracking table and a wrapper function around the PG_NET request functions. This will help us store the required details for each request.

Creating a Request Tracker Table

CREATETABLErequest_tracker(
method TEXT,
url TEXT,
params JSONB,
body JSONB,
headers JSONB,
request_id BIGINT
)

Below is a function called request_wrapper, which wraps around the PG_NET request functions. This function records every request's details in the request_tracker table, facilitating future retries if needed.

Creating a Request Wrapper Function

CREATE OR REPLACEFUNCTIONrequest_wrapper(
method TEXT,
url TEXT,
params JSONB DEFAULT '{}'::JSONB,
body JSONB DEFAULT '{}'::JSONB,
headers JSONB DEFAULT '{}'::JSONB
)
RETURNS BIGINTAS $$
DECLARE
request_id BIGINT;
BEGIN
IF method ='DELETE' THEN
SELECTnet.http_delete(
url:=url,
params:=params,
headers:=headers
) INTO request_id;
ELSIF method ='POST' THEN
SELECTnet.http_post(
url:=url,
body:=body,
params:=params,
headers:=headers
) INTO request_id;
ELSIF method ='GET' THEN
SELECTnet.http_get(
url:=url,
params:=params,
headers:=headers
) INTO request_id;
ELSE
RAISE EXCEPTION 'Method must be DELETE, POST, or GET';
END IF;
INSERT INTO request_tracker (method, url, params, body, headers, request_id)
VALUES (method, url, params, body, headers, request_id);
RETURN request_id;
END;
$$
LANGUAGE plpgsql;

To retry a failed request recorded via the wrapper function, use the following query. This will select failed requests, retry them, and then remove the original request data from both the net._http_response and request_tracker tables.

Retrying failed requests

WITH retry_request AS (
SELECTrequest_tracker.method,
request_tracker.url,
request_tracker.params,
request_tracker.body,
request_tracker.headers,
request_tracker.request_idFROM request_tracker
INNER JOINnet._http_responseONnet._http_response.id =request_tracker.request_idWHEREnet._http_response.status_code >=500LIMIT3
),
retry AS (
SELECT
request_wrapper(retry_request.method, retry_request.url, retry_request.params, retry_request.body, retry_request.headers)
FROM retry_request
),
delete_http_response AS (
DELETEFROMnet._http_responseWHERE id IN (SELECT request_id FROM retry_request)
RETURNING *
)
DELETEFROM request_tracker
WHERE request_id IN (SELECT request_id FROM retry_request)
RETURNING *;

The above function can be called using cron jobs or manually to retry failed requests. It may also be beneficial to clean the request_tracker table in the process.

Contributing

Checkout the Contributing page to learn more about adding to the project.

About

A PostgreSQL extension that enables asynchronous (non-blocking) HTTP/HTTPS requests with SQL

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

368 stars

Watchers

27 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

PG_NET

A PostgreSQL extension that enables asynchronous (non-blocking) HTTP/HTTPS requests with SQL.

Requires libcurl >= 7.83. Compatible with PostgreSQL > = 12.

PostgreSQL versionLicenseCoverage StatusTests


Contents


Introduction

The PG_NET extension enables PostgreSQL to make asynchronous HTTP/HTTPS requests in SQL. It eliminates the need for servers to continuously poll for database changes and instead allows the database to proactively notify external resources about significant events. It seamlessly integrates with triggers, cron jobs (e.g., PG_CRON), and procedures, unlocking numerous possibilities. Notably, PG_NET powers Supabase's Webhook functionality, highlighting its robustness and reliability.

Common use cases for the PG_NET extension include:

  • Calling external APIs
  • Syncing data with outside resources
  • Calling a serverless function when an event, such as an insert, occurred

However, it is important to note that the extension has a few limitations. Currently, it only supports three types of asynchronous requests:

  • async http GET requests
  • async http POST requests with a JSON payload
  • async http DELETE requests

Ultimately, though, PG_NET offers developers more flexibility in how they monitor and connect their database with external resources.


Technical Explanation

The extension introduces a new net schema, which contains two unlogged tables, a type of table in PostgreSQL that offers performance improvements at the expense of durability. You can read more about unlogged tables here. The two tables are:

  1. http_request_queue: This table serves as a queue for requests waiting to be executed. Upon successful execution of a request, the corresponding data is removed from the queue.

    The SQL statement to create this table is:

    CREATE UNLOGGED TABLE
    net.http_request_queue (
    id bigintNOT NULL DEFAULT nextval('net.http_request_queue_id_seq'::regclass),
    method textNOT NULL,
    url textNOT NULL,
    headers jsonb,
    body bytea,
    timeout_milliseconds integerNOT NULL
    )
  2. _http_response: This table holds the responses of each executed request.

    The SQL statement to create this table is:

    CREATE UNLOGGED TABLE
    net._http_response (
    id bigintNULL,
    status_code integerNULL,
    content_type textNULL,
    headers jsonb NULL,
    content textNULL,
    timed_out booleanNULL,
    error_msg textNULL,
    created timestamp with time zoneNOT NULL DEFAULT now()
    )

When any of the three request functions (http_get, http_post, http_delete) are invoked, they create an entry in the net.http_request_queue table.

Once a response is received, it gets stored in the _http_response table. By monitoring this table, you can keep track of response statuses and messages.

Important

Inserting directly into the net.http_request_queue won't cause the worker to process requests, you must use the request functions. We do it this way to avoid polling the net.http_request_queue table, which would pollute pg_stat_statements and cause unnecesssary activity from the worker.

The extension employs C's libcurl library within a PostgreSQL background worker to manage HTTP requests. This background worker sleeps until it receives a signal from the request functions, which awakes it and prompts it to read the net.http_request_queue table and execute the requests on it.


Installation

Clone this repo and run

make && make install

To make the extension available to the database add on postgresql.conf:

shared_preload_libraries = 'pg_net'

By default, pg_net is available on the postgres database. To use pg_net on a different database, you can add the following on postgresql.conf:

pg_net.database_name = '<dbname>';

Using pg_net on multiple databases in a cluster is not yet supported.

To activate the extension in PostgreSQL, run the create extension command. The extension creates its own schema named net to avoid naming conflicts.

create extension pg_net;

Extension Configuration

The extension creates the following configurable variables:

  1. pg_net.batch_size(default: 200): An integer that limits the max number of rows that the extension will process from net.http_request_queue during each read
  2. pg_net.ttl(default: 6 hours): An interval that defines the max time a row in the net.http_response will live before being deleted. Note that this won't happen exactly after the TTL has passed. The worker will perform this deletion while its processing requests.
  3. pg_net.database_name(default: 'postgres'): A string that defines which database the extension is applied to
  4. pg_net.username(default: NULL): A string that defines which user will the background worker be connected with. If not set (NULL), it will assume the bootstrap user.

All these variables can be viewed with the following commands:

show pg_net.batch_size;
show pg_net.ttl;
show pg_net.database_name;
show pg_net.username;

You can change these by editing the postgresql.conf file (find it with SHOW config_file;) or with ALTER SYSTEM:

alter system set pg_net.ttl to '1 hour'
alter system set pg_net.batch_size to 500;

Then, you can reload the settings with:

select pg_reload_conf();

If you change the pg_net.database_name and pg_net.username configs, you'll need to restart the worker for them to apply. We provide a function that reloads the config with pg_reload_conf and restarts the worker in one go:

select net.worker_restart();

Note that doing ALTER SYSTEM requires SUPERUSER but on PostgreSQL >= 15, you can do:

grant alter system on parameter pg_net.ttl to <role>;
grant alter system on parameter pg_net.batch_size to <role>;

To allow regular users to update pg_net settings.

Requests API

GET requests

net.http_get function signature

net.http_get(
-- url for the request
url text,
-- key/value pairs to be url encoded and appended to the `url`
params jsonb default '{}'::jsonb,
-- key/values to be included in request headers
headers jsonb default '{}'::jsonb,
-- the maximum number of milliseconds the request may take before being cancelled
timeout_milliseconds int default 1000
)
-- request_id reference
returns bigint
strict
volatile
parallel safe
language plpgsql

Examples:

The following examples use the Postman Echo API.

Calling an API

SELECTnet.http_get (
'https://postman-echo.com/get?foo1=bar1&foo2=bar2'
) AS request_id;

NOTE: You can view the response with the following query:

SELECT*FROMnet._http_response;

Calling an API with URL encoded params

SELECTnet.http_get(
'https://postman-echo.com/get',
-- Equivalent to calling https://postman-echo.com/get?foo1=bar1&foo2=bar2&encoded=%21-- The "!" is url-encoded as %21'{"foo1": "bar1", "foo2": "bar2", "encoded": "!"}'::JSONB
) AS request_id;

Calling an API with an API-KEY

SELECTnet.http_get(
'https://postman-echo.com/get?foo1=bar1&foo2=bar2',
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id;

POST requests

net.http_post function signature

net.http_post(
-- url for the request
url text,
-- body of the POST request
body jsonb default '{}'::jsonb,
-- key/value pairs to be url encoded and appended to the `url`
params jsonb default '{}'::jsonb,
-- key/values to be included in request headers
headers jsonb default '{"Content-Type": "application/json"}'::jsonb,
-- the maximum number of milliseconds the request may take before being cancelled
timeout_milliseconds int default 1000
)
-- request_id reference
returns bigint
volatile
parallel safe
language plpgsql

Examples:

The following examples post to the Postman Echo API.

Sending data to an API

SELECTnet.http_post(
'https://postman-echo.com/post',
'{"key": "value", "key": 5}'::JSONB,
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id;

Sending single table row as a payload

NOTE: If multiple rows are sent using this method, each row will be sent as a separate request.

WITH selected_row AS (
SELECT*FROM target_table
LIMIT1
)
SELECTnet.http_post(
'https://postman-echo.com/post',
to_jsonb(selected_row.*),
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id
FROM selected_row;

Sending multiple table rows as a payload

WARNING: when sending multiple rows, be careful to limit your payload size.

WITH selected_rows AS (
SELECT-- Converts all the rows into a JSONB array
jsonb_agg(to_jsonb(target_table)) AS JSON_payload
FROM target_table
-- Generally good practice to LIMIT the max amount of rows
)
SELECTnet.http_post(
'https://postman-echo.com/post'::TEXT,
JSON_payload,
headers :='{"API-KEY-HEADER": "<API KEY>"}'::JSONB
) AS request_id
FROM selected_rows;

DELETE requests

net.http_delete function signature

net.http_delete(
-- url for the request
url text,
-- key/value pairs to be url encoded and appended to the `url`
params jsonb default '{}'::jsonb,
-- key/values to be included in request headers
headers jsonb default '{}'::jsonb,
-- the maximum number of milliseconds the request may take before being cancelled
timeout_milliseconds int default 2000
)
-- request_id reference
returns bigint
strict
volatile
parallel safe
language plpgsql
security definer

Examples:

The following examples use the Dummy Rest API.

Sending a delete request to an API

SELECTnet.http_delete(
'https://dummy.restapiexample.com/api/v1/delete/2'
) AS request_id;

Sending a delete request with a row id as a query param

WITH selected_id AS (
SELECT
id
FROM target_table
LIMIT1-- if not limited, it will make a delete request for each returned row
)
SELECTnet.http_delete(
'https://dummy.restapiexample.com/api/v1/delete/'::TEXT,
format('{"id": "%s"}', id)::JSONB
) AS request_id
FROM selected_id;

Sending a delete request with a row id as a path param

WITH selected_id AS (
SELECT
id
FROM target_table
LIMIT1-- if not limited, it will make a delete request for each returned row
)
SELECTnet.http_delete(
'https://dummy.restapiexample.com/api/v1/delete/'|| id
) AS request_id
FROM selected_row

Practical Examples

Syncing data with an external data source using triggers

The following example comes from Typesense's Supabase Sync guide

-- Create the function to delete the record from TypesenseCREATE OR REPLACEFUNCTIONdelete_record()
RETURNS TRIGGER
LANGUAGE plpgSQL
AS $$
BEGINSELECTnet.http_delete(
url := format('<TYPESENSE URL>/collections/products/documents/%s', OLD.id),
headers :='{"X-Typesense-API-KEY": "<Typesense_API_KEY>"}'
)
RETURN OLD;
END $$;
-- Create the trigger that calls the function when a record is deleted from the products tableCREATETRIGGERdelete_products_trigger
AFTER DELETEONpublic.products
FOR EACH ROW
EXECUTE FUNCTION delete_products();

Calling a serverless function every minute with PG_CRON

The PG_CRON extension enables PostgreSQL to become its own cron server. With it you can schedule regular calls to activate serverless functions.

Useful links:

Example Cron job to call serverless function

SELECTcron.schedule(
'cron-job-name',
'* * * * *', -- Executes every minute (cron syntax)
$$
-- SQL querySELECTnet.http_get(
-- URL of Edge function
url:='https://<reference id>.functions.supabase.co/example',
headers:='{ "Content-Type": "application/json", "Authorization": "Bearer <TOKEN>" }'::JSONB
) as request_id;
$$
);

Retrying failed requests

Every request made is logged within the net._http_response table. To identify failed requests, you can execute a query on the table, filtering for requests where the status code is 500 or higher.

Finding failed requests

SELECT*FROMnet._http_responseWHERE status_code >=500;

While the net._http_response table logs each request, it doesn't store all the necessary information to retry failed requests. To facilitate this, we need to create a request tracking table and a wrapper function around the PG_NET request functions. This will help us store the required details for each request.

Creating a Request Tracker Table

CREATETABLErequest_tracker(
method TEXT,
url TEXT,
params JSONB,
body JSONB,
headers JSONB,
request_id BIGINT
)

Below is a function called request_wrapper, which wraps around the PG_NET request functions. This function records every request's details in the request_tracker table, facilitating future retries if needed.

Creating a Request Wrapper Function

CREATE OR REPLACEFUNCTIONrequest_wrapper(
method TEXT,
url TEXT,
params JSONB DEFAULT '{}'::JSONB,
body JSONB DEFAULT '{}'::JSONB,
headers JSONB DEFAULT '{}'::JSONB
)
RETURNS BIGINTAS $$
DECLARE
request_id BIGINT;
BEGIN
IF method ='DELETE' THEN
SELECTnet.http_delete(
url:=url,
params:=params,
headers:=headers
) INTO request_id;
ELSIF method ='POST' THEN
SELECTnet.http_post(
url:=url,
body:=body,
params:=params,
headers:=headers
) INTO request_id;
ELSIF method ='GET' THEN
SELECTnet.http_get(
url:=url,
params:=params,
headers:=headers
) INTO request_id;
ELSE
RAISE EXCEPTION 'Method must be DELETE, POST, or GET';
END IF;
INSERT INTO request_tracker (method, url, params, body, headers, request_id)
VALUES (method, url, params, body, headers, request_id);
RETURN request_id;
END;
$$
LANGUAGE plpgsql;

To retry a failed request recorded via the wrapper function, use the following query. This will select failed requests, retry them, and then remove the original request data from both the net._http_response and request_tracker tables.

Retrying failed requests

WITH retry_request AS (
SELECTrequest_tracker.method,
request_tracker.url,
request_tracker.params,
request_tracker.body,
request_tracker.headers,
request_tracker.request_idFROM request_tracker
INNER JOINnet._http_responseONnet._http_response.id =request_tracker.request_idWHEREnet._http_response.status_code >=500LIMIT3
),
retry AS (
SELECT
request_wrapper(retry_request.method, retry_request.url, retry_request.params, retry_request.body, retry_request.headers)
FROM retry_request
),
delete_http_response AS (
DELETEFROMnet._http_responseWHERE id IN (SELECT request_id FROM retry_request)
RETURNING *
)
DELETEFROM request_tracker
WHERE request_id IN (SELECT request_id FROM retry_request)
RETURNING *;

The above function can be called using cron jobs or manually to retry failed requests. It may also be beneficial to clean the request_tracker table in the process.

Contributing

Checkout the Contributing page to learn more about adding to the project.

About

A PostgreSQL extension that enables asynchronous (non-blocking) HTTP/HTTPS requests with SQL

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

368 stars

Watchers

27 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages