Skip to content

This is the multi-page printable view of this section.

Return to the regular view of this page

Tutorials

Use pgetcd from etcdctl and from a Go client.

These tutorials run against a development tenant and write keys under the /tutorial/ prefix. Reserve /tutorial/ for these exercises.

  1. Complete Quick start first if you do not have a running tenant, and keep the endpoint address and tenant client certificates ready.
  2. Follow Use etcdctl to read and write keys, watch prefix changes from a snapshot revision, and attach or revoke a Lease.
  3. Follow Use the Go client to execute a conditional Txn and watch a key from a known revision with clientv3.

For the full list of supported RPCs and limits, see Compatibility.

1 - Use etcdctl

Put, get, watch and lease keys with etcdctl over mutual TLS.

This exercise writes a key, watches changes from a snapshot revision, and deletes a key by revoking its Lease. It requires a running development tenant (Quick start), etcdctl 3.6.15 (or 3.7.2), and jq. Keep the /tutorial/ prefix free for this walkthrough.

Configure the client

Export the etcd v3 environment variables in each terminal, replacing the endpoint and certificate paths with those for your tenant:

export ETCDCTL_API=3
export ETCDCTL_ENDPOINTS=https://pgetcd.example.test:2379
export ETCDCTL_CACERT=/path/to/server-ca.crt
export ETCDCTL_CERT=/path/to/tenant-client.crt
export ETCDCTL_KEY=/path/to/tenant-client.key
export ETCDCTL_DIAL_TIMEOUT=5s
export ETCDCTL_COMMAND_TIMEOUT=10s

etcdctl version
etcdctl endpoint status --write-out=table

The endpoint hostname or IP must match the gateway server certificate (server.crt), and the client certificate (tenant-client.crt) must carry the tenant’s URI SAN (spiffe://pgetcd/tenant/demo). ETCDCTL_CACERT points to the CA that signed the gateway server certificate.

etcdctl endpoint status prints the tenant’s logical member ID, current revision, advertised version (3.6.0), and PostgreSQL relation size. etcdctl endpoint health reports healthy from v0.1.0-rc2; on v0.1.0-rc1 it fails because Maintenance.Alarm was unimplemented. If endpoint status fails, see Troubleshooting.

Read and write keys

Write and read back a key under /tutorial/:

etcdctl put /tutorial/hello world
etcdctl get /tutorial/hello
etcdctl get /tutorial/ --prefix --write-out=json

The first command prints OK. The second prints the key and world. The JSON output shows header.revision along with the key’s create_revision, mod_revision, and version (keys and values in JSON output are base64-encoded).

Write the same value a second time:

etcdctl put /tutorial/hello world
etcdctl get /tutorial/hello --write-out=json

Both version and mod_revision advance even when the value does not change. Do not hard-code revision numbers in scripts; concurrent writes or Lease expirations in the same tenant also advance the revision counter.

Read a snapshot, then watch

In the first terminal, read a prefix snapshot and start a Watch at header.revision + 1:

TUTORIAL_SNAPSHOT=$(etcdctl get /tutorial/ --prefix --write-out=json)
printf '%s\n' "$TUTORIAL_SNAPSHOT" | jq .
TUTORIAL_START=$(printf '%s\n' "$TUTORIAL_SNAPSHOT" | jq '.header.revision + 1')
etcdctl --command-timeout=0s watch /tutorial/ --prefix --prev-kv --rev="$TUTORIAL_START"

In a second terminal with the same ETCDCTL_* variables, update and delete the key:

etcdctl put /tutorial/hello updated
etcdctl del /tutorial/hello

The first terminal prints PUT and DELETE events with their previous key-value pairs (--prev-kv). Passing --rev="$TUTORIAL_START" ensures that any write committed between the get snapshot and the watch registration is still delivered, provided that revision has not been logically compacted.

Press Ctrl-C to stop the Watch. If the requested start revision has been compacted, take a fresh get snapshot and start a new Watch. For Watch stream and buffer limits, see Troubleshooting — Capacity.

Note

jq uses IEEE 754 double-precision numbers. For production applications where revisions can exceed $2^{53} - 1$, compute revision + 1 in a client that preserves 64-bit integers, such as the Go client example.

Attach and revoke a Lease

Grant a 30-second Lease:

etcdctl lease grant 30

Copy the hexadecimal Lease ID from the output and attach /tutorial/leased to it:

TUTORIAL_LEASE=0123456789abcdef
etcdctl put /tutorial/leased temporary --lease="$TUTORIAL_LEASE"
etcdctl lease timetolive "$TUTORIAL_LEASE" --keys
etcdctl lease revoke "$TUTORIAL_LEASE"
etcdctl get /tutorial/leased

Revoking the Lease atomically deletes /tutorial/leased in the same PostgreSQL transaction, so the final get returns no rows.

To keep a Lease alive continuously, grant a new Lease and run etcdctl --command-timeout=0s lease keep-alive <lease-id>. For Lease recovery behavior after a PostgreSQL restart, see Watch, Lease and history.

Clean up

Delete any remaining keys under /tutorial/:

etcdctl del /tutorial/ --prefix

Next, see Use the Go client for conditional transactions.

2 - Use the Go client

Connect clientv3 with tenant certificates and run transactions and watches.

This example uses the official go.etcd.io/etcd/client/v3 package (v3.7.2 in the pgetcd go.mod) to connect to a running development tenant over mutual TLS, execute a conditional Txn on /tutorial/go-client, and watch the next write starting from Header.Revision + 1.

Export the ETCDCTL_* environment variables from Use etcdctl before running the program.

Write the program

Create .cache/tutorial-client/main.go inside the pgetcd checkout (.cache/ is ignored by Git):

package main

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"errors"
	"fmt"
	"os"
	"time"

	clientv3 "go.etcd.io/etcd/client/v3"
)

func main() {
	if err := run(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func run() error {
	if len(os.Args) != 5 {
		return errors.New("usage: client <endpoint> <server-ca> <client-cert> <client-key>")
	}
	ca, err := os.ReadFile(os.Args[2])
	if err != nil {
		return err
	}
	roots := x509.NewCertPool()
	if !roots.AppendCertsFromPEM(ca) {
		return errors.New("invalid server CA")
	}
	cert, err := tls.LoadX509KeyPair(os.Args[3], os.Args[4])
	if err != nil {
		return err
	}
	client, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{os.Args[1]},
		DialTimeout: 5 * time.Second,
		TLS: &tls.Config{
			MinVersion:   tls.VersionTLS12,
			RootCAs:      roots,
			Certificates: []tls.Certificate{cert},
		},
	})
	if err != nil {
		return err
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancel()
	const key = "/tutorial/go-client"
	initial, err := client.Txn(ctx).
		If(clientv3.Compare(clientv3.Version(key), "=", 0)).
		Then(clientv3.OpPut(key, "hello")).
		Else(clientv3.OpGet(key)).
		Commit()
	if err != nil {
		return fmt.Errorf("initial transaction: %w", err)
	}
	fmt.Printf("created=%t revision=%d\n", initial.Succeeded, initial.Header.Revision)

	changes := client.Watch(ctx, key, clientv3.WithRev(initial.Header.Revision+1))
	written, err := client.Put(ctx, key, "updated")
	if err != nil {
		return fmt.Errorf("put: %w", err)
	}
	for response := range changes {
		if err := response.Err(); err != nil {
			return fmt.Errorf("watch: %w", err)
		}
		for _, event := range response.Events {
			if event.Kv.ModRevision == written.Header.Revision {
				fmt.Printf("%s %s=%s revision=%d\n",
					event.Type, event.Kv.Key, event.Kv.Value, event.Kv.ModRevision)
				return nil
			}
		}
	}
	if err := ctx.Err(); err != nil {
		return err
	}
	return errors.New("watch closed before the write was observed")
}

Run the program

From the pgetcd repository root, run:

go run ./.cache/tutorial-client \
  "$ETCDCTL_ENDPOINTS" "$ETCDCTL_CACERT" "$ETCDCTL_CERT" "$ETCDCTL_KEY"

Pass a single endpoint URL in ETCDCTL_ENDPOINTS. The first run prints created=true followed by the PUT event for updated. Subsequent runs print created=false because Version(key) is no longer 0.

Starting the Watch at initial.Header.Revision + 1 avoids a race between Watch registration and Put: even if Put commits before the Watch stream finishes registering, pg_etcd replays retained events from initial.Header.Revision + 1 onward.

All operations share a 15-second context timeout. If a write times out or returns an unknown outcome, do not blindly replay a non-idempotent write; inspect the committed state first.

Clean up and production notes

Delete the tutorial key when done:

etcdctl del /tutorial/go-client

When writing production clientv3 consumers:

  • Persist your consumer’s resume revision only after processing all events of a complete revision.
  • If a Watch response carries CompactRevision > 0 (ErrCompacted), take a fresh Get snapshot and open a new Watch from Header.Revision + 1.
  • If stream fragmentation is enabled, wait until More == false before treating a revision as complete.

For more details on Watch tailing and Lease lifecycles, see Watch, Lease and history.