Database Access on the Edge with Cloudflare Workers & Prisma

Rate this content
Bookmark

Edge functions are pushing the limit of serverless computing – but with new tools, come new challenges. Due to their limitations, edge functions don't allow talking to popular databases like PostgreSQL and MySQL. In this talk, you will learn how you can connect and interact with your database from Cloudflare Workers using the Prisma Data Proxy.


You can check the slides for Alex's talk here

FAQ

Cloud Flarewalkers refers to CloudFlare's edge computing solution, which facilitates serverless compute that is distributed across CloudFlare's network of data centers. Unlike traditional serverless platforms that operate from specific data centers, Cloud Flarewalkers run your application code much closer to your users, potentially even in the same city.

CloudFlare workers are built on the V8 engine and are significantly lighter, unlike traditional serverless platforms that may require provisioning a full container. This allows CloudFlare workers to have shorter startup times and lower latency, as the code is executed closer to the user and the environment is lighter.

Despite the advantages, CloudFlare workers face challenges similar to other serverless platforms in terms of database connectivity. They primarily support HTTP-based connections, while traditional databases rely on long-lived TCP connections, making it difficult to manage database connections effectively in a stateless serverless environment.

Prisma is a next-gen type-safe ORM for Node.js that supports several databases and enhances developer productivity through intuitive data querying methods and type safety. In the context of CloudFlare workers, Prisma can be integrated using the Prisma Data Proxy, which manages database connections and pools effectively, facilitating smoother interactions between your serverless functions and your database.

The Prisma Data Proxy acts as an intermediary between serverless functions and databases, handling connection pooling to prevent the exhaustion of database connections. This is particularly beneficial for applications running on the edge, as it allows them to utilize traditional relational databases without facing the common connectivity issues associated with serverless environments.

Migrating an application involves setting up the Prisma environment, defining data models, and integrating the Prisma client into your application to replace direct database interactions. The application's routes are updated to fetch and manipulate data using Prisma's queries instead of direct database calls, and the Prisma Data Proxy is used to manage connections.

Deploying on the edge with CloudFlare workers can significantly reduce latency, improve application performance, and enhance user experience by running computation closer to users. This distributed approach also allows for high scalability and efficient content delivery across different geographical locations.

Alex Ruheni
Alex Ruheni
31 min
17 Feb, 2022

Comments

Sign in or register to post your comment.

Video Summary and Transcription

This Talk discusses database access on the edge with CloudFlare workers and the challenges of serverless platforms. It explores solutions for database access, including CloudFlare-specific solutions and using Prisma data proxy. The Prisma toolkit and demo are showcased, demonstrating how to convert an application to use a database. The process of setting up Prisma Data Platform and deploying the application to CloudFlare workers is explained. The Talk concludes with insights on database usage and the differences between serverless, CDN, and the Edge.

1. Introduction to Cloud Flarewalkers

Short description:

Hello, friends. Today I'll be talking about database access on the edge with Cloud Flarewalkers. We'll discuss what it is, how different it is from the traditional serverless platforms and the growing pains of serverless. CloudFlare workers run your application code much closer to your user, which could even be in the same city. CloudFlare workers are significantly lighter because the platform is built on top of the V8 engine. CloudFlare workers also provide high performance, with shorter start-up time and lower latency. However, connecting to databases is still a challenge from CloudFlare workers due to the limitations of the V8 engine.

Hello, friends. Today I'll be talking about database access on the edge with Cloud Flarewalkers. My name is Alex, and I'm a developer advocate at Prisma. Feel free to reach out to me after the talk if you have any questions, or just any random questions or connect.

This talk will be divided into four sections. The first part will be about Cloud Flarewalkers, or the edge. We'll discuss what it is, how different it is from the traditional serverless platforms and the growing pains of serverless. The second section will take a look at Prisma and the Prisma Data Proxy, exploring how the Data Proxy helps you interact with your database on the edge. And the third part, or the third section, will be the exciting bit, where we will have a demo. We'll migrate an application using a JSON file for storing and retrieving quotes, and move over the data to a database and deploy it to the edge. Finally we'll have a recap of the talk on the end. And for now, let's jump into it.

So what is the edge? It seems to be a buzzword that's used a lot, but what does it mean? The edge is a form of serverless compute that's distributed. And in the context of CloudFlare workers, it's deployed to CloudFlare's network of data centers.

Now that you understand what the edge is, and how CloudFlare works, let's take a look at how CloudFlare workers are different from traditional serverless. As I mentioned before, it's distributed. Traditional serverless functions are deployed to specific data centers or region. And in contrast, CloudFlare workers run your application code much closer to your user, which could even be in the same city. CloudFlare workers are also significantly lighter because the platform is built on top of the V8 engine. It's the same engine that powers Chromium-based browsers such as Chrome and Edge, and also the Node.js runtime. So whenever your CloudFlare worker is invoked, instead of provisioning an intact container for your serverless function, CloudFlare worker spins up a V8 isolate that is significantly smaller. And if you've heard about the cold start problem on serverless, then you understand why this is an exciting technology.

So CloudFlare workers also provide high performance. This is adding on top of the first two points. Because the environment is significantly lighter, which leads to a shorter start up time, or even possibly none. And you also would experience lower latency whenever you invoke your function because it would be invoked from the data center that is closest to you. Now I know this all sounds delightful, but CloudFlare workers still suffer from the same problems that traditional serverless functions do in the context of databases. So connecting to databases is still a challenge from CloudFlare workers. This is because V8 engine supports sending only HTTP-based connections. However, traditional databases depend on long-lived TCP connections.

2. Challenges and Solutions for Database Access

Short description:

Different databases have different implementations for connecting to them, which can be chaotic. Database connections in serverless environments can easily run out, causing requests to fail. Possible solutions include CloudFlare specific solutions, using Postgres to convert an existing database into a RESTful API, modifying Postgres and MySQL drivers to use HTTP with Deno, and using the Prisma data proxy.

This becomes a bummer. The different databases present different implementations of the interfaces of how you can connect to them, which is all chaotic and it's on. Database connections are also stateful, while serverless environments are stateless, meaning that you can easily run out of database connections because every worker creates a new connection pool. And when you run out of connections, requests in your application would start failing.

So how can you solve this problem? Well, you have a number of options available to you, just like in the rest of the JavaScript ecosystem. One option would be to go with CloudFlare specific solutions such as worker's key value store and durable objects. The second option, if you have an existing database, you could use Postgres, which converts your existing Postgres database into a RESTful API. Another option would be to convert, to use the Postgres and MySQL drivers and modifying them to use HTTP using Deno, I believe. And finally the gist of this talk, which is the Prisma data proxy and this talk will focus on this, but feel free to try out the other options for yourself as well.

So Prisma is a next-gen type-safe ORM for NodeJS that works with both JavaScript and TypeScript. It supports a number of databases such as SQLite, MySQL, Postgres, SQL server, and also CockroachDB and MongoDB, which are still in preview. The core benefits of Prisma is that it boosts productivity by letting developers query data in natural and familiar ways, and also providing a human readable data model. Prisma also increases developer confidence with the type safety, the auto-completion, and the robust API for interacting with your database. So even if you don't use TypeScript in your project, most editors will provide auto-completion for your database queries when you're using Prisma.

QnA

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

It's a Jungle Out There: What's Really Going on Inside Your Node_Modules Folder
Node Congress 2022Node Congress 2022
26 min
It's a Jungle Out There: What's Really Going on Inside Your Node_Modules Folder
Top Content
Do you know what’s really going on in your node_modules folder? Software supply chain attacks have exploded over the past 12 months and they’re only accelerating in 2022 and beyond. We’ll dive into examples of recent supply chain attacks and what concrete steps you can take to protect your team from this emerging threat.
You can check the slides for Feross' talk here.
Towards a Standard Library for JavaScript Runtimes
Node Congress 2022Node Congress 2022
34 min
Towards a Standard Library for JavaScript Runtimes
Top Content
You can check the slides for James' talk here.
ESM Loaders: Enhancing Module Loading in Node.js
JSNation 2023JSNation 2023
22 min
ESM Loaders: Enhancing Module Loading in Node.js
Native ESM support for Node.js was a chance for the Node.js project to release official support for enhancing the module loading experience, to enable use cases such as on the fly transpilation, module stubbing, support for loading modules from HTTP, and monitoring.
While CommonJS has support for all this, it was never officially supported and was done by hacking into the Node.js runtime code. ESM has fixed all this. We will look at the architecture of ESM loading in Node.js, and discuss the loader API that supports enhancing it. We will also look into advanced features such as loader chaining and off thread execution.
Out of the Box Node.js Diagnostics
Node Congress 2022Node Congress 2022
34 min
Out of the Box Node.js Diagnostics
In the early years of Node.js, diagnostics and debugging were considerable pain points. Modern versions of Node have improved considerably in these areas. Features like async stack traces, heap snapshots, and CPU profiling no longer require third party modules or modifications to application source code. This talk explores the various diagnostic features that have recently been built into Node.
You can check the slides for Colin's talk here. 
Living on the Edge
React Advanced Conference 2021React Advanced Conference 2021
36 min
Living on the Edge
React 18 introduces new APIs for rendering applications asynchronously on the server, enabling a simpler model for architecting and shipping user interfaces. When deployed on edge networking platforms like Cloudflare Workers, we can get dramatic performance and user experience improvements in our applications. In this talk, Sunil will demo and walk through this new model of writing React applications, with some insight into the implications for data fetching, styling, and overall direction of the React ecosystem.
Node.js Compatibility in Deno
Node Congress 2022Node Congress 2022
34 min
Node.js Compatibility in Deno
Can Deno run apps and libraries authored for Node.js? What are the tradeoffs? How does it work? What’s next?

Workshops on related topic

How to Solve Real-World Problems with Remix
Remix Conf Europe 2022Remix Conf Europe 2022
195 min
How to Solve Real-World Problems with Remix
Featured Workshop
Michael Carter
Michael Carter
- Errors? How to render and log your server and client errorsa - When to return errors vs throwb - Setup logging service like Sentry, LogRocket, and Bugsnag- Forms? How to validate and handle multi-page formsa - Use zod to validate form data in your actionb - Step through multi-page forms without losing data- Stuck? How to patch bugs or missing features in Remix so you can move ona - Use patch-package to quickly fix your Remix installb - Show tool for managing multiple patches and cherry-pick open PRs- Users? How to handle multi-tenant apps with Prismaa - Determine tenant by host or by userb - Multiple database or single database/multiple schemasc - Ensures tenant data always separate from others
End-To-End Type Safety with React, GraphQL & Prisma
React Advanced Conference 2022React Advanced Conference 2022
95 min
End-To-End Type Safety with React, GraphQL & Prisma
Featured WorkshopFree
Sabin Adams
Sabin Adams
In this workshop, you will get a first-hand look at what end-to-end type safety is and why it is important. To accomplish this, you’ll be building a GraphQL API using modern, relevant tools which will be consumed by a React client.
Prerequisites: - Node.js installed on your machine (12.2.X / 14.X)- It is recommended (but not required) to use VS Code for the practical tasks- An IDE installed (VSCode recommended)- (Good to have)*A basic understanding of Node.js, React, and TypeScript
Relational Database Modeling for GraphQL
GraphQL Galaxy 2020GraphQL Galaxy 2020
106 min
Relational Database Modeling for GraphQL
Top Content
WorkshopFree
Adron Hall
Adron Hall
In this workshop we'll dig deeper into data modeling. We'll start with a discussion about various database types and how they map to GraphQL. Once that groundwork is laid out, the focus will shift to specific types of databases and how to build data models that work best for GraphQL within various scenarios.
Table of contentsPart 1 - Hour 1      a. Relational Database Data Modeling      b. Comparing Relational and NoSQL Databases      c. GraphQL with the Database in mindPart 2 - Hour 2      a. Designing Relational Data Models      b. Relationship, Building MultijoinsTables      c. GraphQL & Relational Data Modeling Query Complexities
Prerequisites      a. Data modeling tool. The trainer will be using dbdiagram      b. Postgres, albeit no need to install this locally, as I'll be using a Postgres Dicker image, from Docker Hub for all examples      c. Hasura
Node.js Masterclass
Node Congress 2023Node Congress 2023
109 min
Node.js Masterclass
Top Content
Workshop
Matteo Collina
Matteo Collina
Have you ever struggled with designing and structuring your Node.js applications? Building applications that are well organised, testable and extendable is not always easy. It can often turn out to be a lot more complicated than you expect it to be. In this live event Matteo will show you how he builds Node.js applications from scratch. You’ll learn how he approaches application design, and the philosophies that he applies to create modular, maintainable and effective applications.

Level: intermediate
Build and Deploy a Backend With Fastify & Platformatic
JSNation 2023JSNation 2023
104 min
Build and Deploy a Backend With Fastify & Platformatic
WorkshopFree
Matteo Collina
Matteo Collina
Platformatic allows you to rapidly develop GraphQL and REST APIs with minimal effort. The best part is that it also allows you to unleash the full potential of Node.js and Fastify whenever you need to. You can fully customise a Platformatic application by writing your own additional features and plugins. In the workshop, we’ll cover both our Open Source modules and our Cloud offering:- Platformatic OSS (open-source software) — Tools and libraries for rapidly building robust applications with Node.js (https://oss.platformatic.dev/).- Platformatic Cloud (currently in beta) — Our hosting platform that includes features such as preview apps, built-in metrics and integration with your Git flow (https://platformatic.dev/). 
In this workshop you'll learn how to develop APIs with Fastify and deploy them to the Platformatic Cloud.
0 to Auth in an Hour Using NodeJS SDK
Node Congress 2023Node Congress 2023
63 min
0 to Auth in an Hour Using NodeJS SDK
WorkshopFree
Asaf Shen
Asaf Shen
Passwordless authentication may seem complex, but it is simple to add it to any app using the right tool.
We will enhance a full-stack JS application (Node.JS backend + React frontend) to authenticate users with OAuth (social login) and One Time Passwords (email), including:- User authentication - Managing user interactions, returning session / refresh JWTs- Session management and validation - Storing the session for subsequent client requests, validating / refreshing sessions
At the end of the workshop, we will also touch on another approach to code authentication using frontend Descope Flows (drag-and-drop workflows), while keeping only session validation in the backend. With this, we will also show how easy it is to enable biometrics and other passwordless authentication methods.
Table of contents- A quick intro to core authentication concepts- Coding- Why passwordless matters
Prerequisites- IDE for your choice- Node 18 or higher