# AWS Lightsail

[AWS Lightsail](https://aws.amazon.com/lightsail/) provides a small dual-stack VM, a reassignable static IPv4 address, and an external firewall managed with [OpenTofu](https://opentofu.org/).

On the cheapest Lightsail bundle (`nano_3_0`: 2 burstable vCPUs, 512 MB RAM, ~180 MB free after OS services) running Ubuntu 24.04 with `GOMEMLIMIT=160MiB` and 7.5 MB kernel UDP buffers, we measured ([Performance](https://vagus.neuroplast.io/docs/performance#example-results-2-vcpu-512-mb-vm)):

| Workload | Measured clean capacity on `nano_3_0` |
| --- | --- |
| QUIC forwarding | 1,000 routes opened at 18,000/s; 50,000 pkt/s (60 MB/s), 0% loss |
| WebSocket throughput | 123 MB/s each way (4 sessions), 109 MB/s (64), 66 MB/s (1,024) |
| Idle WebSocket sessions | 3,000 concurrent sessions (153 MB RSS, ~60 KB/session) |
| Session open rate | 1,200 new WebSocket sessions/s (p99 37 ms) |

Choose a larger bundle only for its monthly data transfer allowance (the relay transmits every proxied byte in both directions) or if you need more than 3,000 concurrent sessions. On a 512 MB `nano_3_0` VM, running the signed Linux binary under systemd avoids Docker daemon memory overhead and preserves the full ~180 MB free RAM above.

## 1. OpenTofu manifest

Save the following as `main.tf`. It creates a dual-stack Lightsail instance, attaches a static IPv4 address, configures the external firewall (keeping TCP 22 restricted to Lightsail's browser SSH console), and installs the relay on first boot:

```hcl
terraform {
  required_version = ">= 1.9"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 5.0"
    }
  }
}

variable "region" {
  type    = string
  default = "eu-central-1"
}

variable "zone" {
  type    = string
  default = "a"
}

variable "bundle" {
  type    = string
  default = "nano_3_0"
}

variable "domain" {
  type        = string
  description = "Routing domain (for example, relay.example.com)"
}

variable "acme_email" {
  type        = string
  description = "Contact email for Let's Encrypt"
}

provider "aws" {
  region = var.region
}

resource "aws_lightsail_instance" "relay" {
  name              = "vagus-relay"
  availability_zone = "${var.region}${var.zone}"
  blueprint_id      = "ubuntu_24_04"
  bundle_id         = var.bundle
  ip_address_type   = "dualstack"
  user_data = templatefile("${path.module}/relay-launch.sh.tftpl", {
    domain = var.domain
    email  = var.acme_email
  })
  tags = { service = "vagus" }
}

resource "aws_lightsail_static_ip" "relay" {
  name = "vagus-relay"
}

resource "aws_lightsail_static_ip_attachment" "relay" {
  instance_name  = aws_lightsail_instance.relay.name
  static_ip_name = aws_lightsail_static_ip.relay.name
}

resource "aws_lightsail_instance_public_ports" "relay" {
  instance_name = aws_lightsail_instance.relay.name

  # Browser console SSH only; add your IP temporarily when needed.
  port_info {
    protocol          = "tcp"
    from_port         = 22
    to_port           = 22
    cidrs             = []
    cidr_list_aliases = ["lightsail-connect"]
  }

  # For a private relay, restrict UDP 19451 to your connectors' CIDRs.
  dynamic "port_info" {
    for_each = {
      acme      = ["tcp", 80]
      https     = ["tcp", 443]
      quic      = ["udp", 443]
      connector = ["udp", 19451]
    }
    content {
      protocol   = port_info.value[0]
      from_port  = tonumber(port_info.value[1])
      to_port    = tonumber(port_info.value[1])
      cidrs      = ["0.0.0.0/0"]
      ipv6_cidrs = ["::/0"]
    }
  }
}

output "ipv4" {
  value = aws_lightsail_static_ip.relay.ip_address
}

output "ipv6" {
  value = aws_lightsail_instance.relay.ipv6_addresses
}
```

## 2. First-boot launch template

Save the following next to `main.tf` as `relay-launch.sh.tftpl`. On first boot it raises kernel UDP socket buffers, waits for DNS to resolve to the attached static IP to fetch a Let's Encrypt certificate, and installs [`engram follow`](https://vagus.neuroplast.io/docs/operations#binary-and-systemd), which installs the newest signed `vagus` build from the stable channel, starts `vagus-relay.service`, and keeps it current from then on:

```sh
#!/bin/sh
set -eu
domain='${domain}'
email='${email}'
# vagus's release key; it signs engram's builds too.
signer='release@neuroplast.io namespaces="engram" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDCsEZcn1tiubvKQzEVs5pJ4QVXoFmSDtO+k6SdetUdf'

apt-get update
apt-get install -y certbot curl openssh-client

# Raise kernel UDP socket buffers for QUIC Initial bursts.
cat > /etc/sysctl.d/99-vagus.conf <<'SYSCTL'
net.core.rmem_max = 7500000
net.core.wmem_max = 7500000
SYSCTL
sysctl --system

# Retry certbot until DNS resolves to the attached static IP.
until certbot certonly --standalone --non-interactive --agree-tos \
  -m "$email" -d "control.$domain"; do
  sleep 60
done
printf '#!/bin/sh\nsystemctl try-restart vagus-relay.service\n' \
  > /etc/letsencrypt/renewal-hooks/deploy/vagus-relay
chmod 0755 /etc/letsencrypt/renewal-hooks/deploy/vagus-relay

cat > /etc/systemd/system/vagus-relay.service <<UNIT
[Unit]
Description=vagus relay
After=network-online.target
Wants=network-online.target

[Service]
Environment=GOMEMLIMIT=160MiB
ExecStart=/var/lib/engram/vagus/bin/vagus relay -public 0.0.0.0:443 -control 0.0.0.0:19451 -https 0.0.0.0:443 -domain $domain -cert %d/control.pem -key %d/control.key
LoadCredential=control.pem:/etc/letsencrypt/live/control.$domain/fullchain.pem
LoadCredential=control.key:/etc/letsencrypt/live/control.$domain/privkey.pem
DynamicUser=yes
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
Restart=on-failure
KillSignal=SIGINT
TimeoutStopSec=65min
RestartSec=2s

[Install]
WantedBy=multi-user.target
UNIT
systemctl daemon-reload
# Enabled, not started: the follower's first restart starts it.
systemctl enable vagus-relay.service

mkdir -p /etc/vagus
cat > /etc/vagus/engram.conf <<CONF
url = https://pkg.neuroplast.io
project = engram
channel = stable
signer = $signer
self = true
CONF
cat > /etc/vagus/vagus.conf <<CONF
url = https://pkg.neuroplast.io
project = vagus
channel = stable
signer = $signer
unit = vagus-relay.service
listen = tcp:443 udp:443 udp:19451
CONF
curl -fsS https://pkg.neuroplast.io/engram/install.sh |
  ENGRAM_SIGNERS="$signer" sh -s -- engram /usr/local/bin
/usr/local/bin/engram follow install /etc/vagus/engram.conf
/usr/local/bin/engram follow install /etc/vagus/vagus.conf
```

Adjust `GOMEMLIMIT` if you change `var.bundle` to an instance larger than 512 MB.

## 3. Apply and configure DNS

Initialize and apply the manifest with AWS credentials configured in your environment:

```sh
tofu init
tofu apply -var domain=relay.example.com -var acme_email=you@example.com
```

Create `A` records for `control.relay.example.com` and `*.relay.example.com` using the `ipv4` output, and `AAAA` records using the `ipv6` output (Lightsail static IPs are IPv4-only, so update `AAAA` whenever you replace the instance). Within a minute of DNS propagation, the first-boot script completes ACME issuance and the follower starts `vagus-relay.service`. `journalctl -u engram-follow@vagus` shows what it installed, and each newer build is installed the same way, after the relay drains.

From there, pin issuance with a CAA record and attach a service following [Self-hosting](https://vagus.neuroplast.io/docs/self-hosting#5-attach-a-service).

## Operational notes

- Each relay keeps its active routes, admission tickets, and handoff invitations in memory, so never put two `A` records behind one relay hostname. To run multiple relays (for example across availability zones or regions), give each instance its own DNS label such as `euc1a.relay.example.com` and `euc1b.relay.example.com` (see [Supervision, failover, and upgrades](https://vagus.neuroplast.io/docs/operations#supervision-failover-and-upgrades)).
- Rebuilding the instance reattaches the same static IPv4 address automatically, but registers a new ACME account. If your CAA record pins `accounturi`, restore `/etc/letsencrypt/accounts` before certbot runs or update the CAA record afterward. Restore any Turnstile secret file before starting the relay.
- To prevent accidental replacement during routine `tofu apply` runs, add `lifecycle { prevent_destroy = true }` to `aws_lightsail_instance.relay`.
