PostgreSQL: Generating UUID primary keys
A universally unique identifier (UUID) is a 128-bit number that is generated in a way that makes it very unlikely that the same identifier will be generated by anyone else in the known universe (globally unique).
In PostgreSQL, you can generate UUIDs using the uuid_generate_v4
function from the uuid-ossp
extension.
What is UUID?
When to use UUIDs?
You can use UUIDs when you need to generate a globally unique indentifier without using an id generation service, for example, OpenTelemetry uses 16-bytes identifiers as a trace id.
Usually, UUIDs are generated by taking 16 random bytes and the uniqueness is based on the sheer quantity, not the generation algorithm. Such identifiers are proven to be unique, but are larger and slightly slower than 64-bit sequential numbers.
TIP
UUIDs are slightly slower than 64-bit sequential identifiers. Use them only when you don't have an easy way to generate smaller sequential identifiers.
UUID in PostgreSQL
PostgreSQL requires an extension to support UUID column type. The extenstion comes with postgresql-contrib-*
package:
sudo apt install postgresql-contrib-14
Then you need to install the extension in each database where you are going to use it:
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
UUID in Go
For working with UUIDs in Go you need to install google/uuid package.
go get github.com/google/uuid
satori/go.uuid works too, but it does not look maintained any more.
Generating UUIDs
In PostgreSQL:
SELECT uuid_generate_v4();
In Go:
import "github.com/google/uuid"
fmt.Println(uuid.New())
Using UUIDs in models
You can use uuid.UUID
type in Bun models like this:
import "github.com/google/uuid"
type Story struct {
ID uuid.UUID `bun:"type:uuid,default:uuid_generate_v4()"`
Title string
AuthorID uuid.UUID `bun:"type:uuid"`
}
UUID
field name also works well:
type Story struct {
UUID uuid.UUID `bun:",pk,type:uuid,default:uuid_generate_v4()"`
Title string
AuthorUUID uuid.UUID `bun:"type:uuid"`
}
Monitoring performance
To monitor Bun performance, you can use OpenTelemetry instrumentation that comes with Bun and Uptrace.
Uptrace is a source-available APM powered by OpenTelemetry and ClickHouse. It allows you to identify and fix bugs in production faster knowing what conditions lead to which errors.
You can get started with Uptrace by downloading a DEB/RPM package or a pre-compiled Go binary.