Skip to main content
Aiven for PostgreSQL is a fully managed, high-performance relational database service that offers maximum flexibility with advanced extensions including pgvector for AI-powered search, PostGIS for geospatial queries, and TimescaleDB for time-series data.

Overview

PostgreSQL is a powerful open-source relational database ideal for organizations needing well-structured tabular data storage. Aiven for PostgreSQL provides enterprise-grade reliability, automated operations, and advanced features out of the box.

Why Choose Aiven for PostgreSQL

AI-Powered Search

Built-in pgvector extension for semantic search and similarity matching using vector embeddings

Advanced Extensions

PostGIS for location queries, TimescaleDB for time-series, and 50+ extensions available

High Availability

Multi-node clusters with automatic failover and 99.99% SLA on business plans

Native JSON Support

Store and query nested datasets with native jsonb format for flexible schemas

Key Features

Enable AI-powered similarity search and vector operations:
  • Store ML-generated embeddings directly in PostgreSQL
  • Perform semantic search across text, images, and more
  • Support for exact and approximate nearest neighbor search
  • Index types: IVFFlat and HNSW for performance
Use Cases:
  • Recommendation systems
  • Semantic document search
  • Image similarity detection
  • Fraud detection through pattern matching
Example:
-- Enable pgvector
CREATE EXTENSION vector;

-- Create table with vector column
CREATE TABLE items (
  id SERIAL PRIMARY KEY,
  name TEXT,
  embedding vector(1536)
);

-- Create HNSW index for fast similarity search
CREATE INDEX ON items USING hnsw (embedding vector_cosine_ops);

-- Find similar items
SELECT name, 1 - (embedding <=> '[0.1, 0.2, ...]') AS similarity
FROM items
ORDER BY embedding <=> '[0.1, 0.2, ...]'
LIMIT 10;
Advanced spatial database capabilities:
  • Store points, lines, polygons, and complex geometries
  • Spatial indexing with GiST and SP-GiST
  • Distance calculations and proximity queries
  • Map projections and coordinate transformations
Example:
CREATE EXTENSION postgis;

CREATE TABLE locations (
  id SERIAL PRIMARY KEY,
  name TEXT,
  location GEOGRAPHY(POINT, 4326)
);

-- Find locations within 1000 meters
SELECT name 
FROM locations 
WHERE ST_DWithin(
  location, 
  ST_GeogFromText('POINT(-122.4194 37.7749)'), 
  1000
);
Optimized for time-series and IoT data:
  • Automatic partitioning by time
  • Continuous aggregates for real-time rollups
  • Data retention policies
  • Compression for storage efficiency
Example:
CREATE EXTENSION timescaledb;

CREATE TABLE sensor_data (
  time TIMESTAMPTZ NOT NULL,
  sensor_id INTEGER,
  temperature DOUBLE PRECISION,
  humidity DOUBLE PRECISION
);

SELECT create_hypertable('sensor_data', 'time');

-- Query with time-bucketing
SELECT time_bucket('1 hour', time) AS hour,
       sensor_id,
       avg(temperature) AS avg_temp
FROM sensor_data
WHERE time > NOW() - INTERVAL '24 hours'
GROUP BY hour, sensor_id;
Built-in PgBouncer for efficient connection management:
  • Reduce connection overhead
  • Session, transaction, and statement pooling modes
  • Handle thousands of client connections
  • Automatic connection recycling
Multi-region replication for business continuity:
  • Asynchronous replication across regions
  • Failover to secondary region
  • Switchover for planned maintenance
  • RPO (Recovery Point Objective) in seconds

Getting Started

1

Create PostgreSQL Service

Deploy a PostgreSQL service through Aiven Console, CLI, or API:
avn service create my-pg \
  --service-type pg \
  --cloud aws-us-east-1 \
  --plan business-4
Choose from multiple service plans:
  • Hobbyist: Single node for development
  • Startup: Single node for small apps
  • Business: High availability with standby
  • Premium: Enhanced HA with 2 standby nodes
2

Enable Extensions

Enable extensions you need for your use case:
CREATE EXTENSION IF NOT EXISTS pgvector;      -- Vector search
CREATE EXTENSION IF NOT EXISTS postgis;       -- Geospatial
CREATE EXTENSION IF NOT EXISTS timescaledb;   -- Time-series
CREATE EXTENSION IF NOT EXISTS pg_stat_statements; -- Query stats
3

Create Database and Tables

Set up your database schema:
CREATE DATABASE myapp;
\c myapp

CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  email TEXT UNIQUE NOT NULL,
  name TEXT,
  created_at TIMESTAMPTZ DEFAULT NOW()
);
4

Connect Your Application

Use the connection string from the service overview to connect your application.

Connection Examples

import psycopg2
from psycopg2.extras import RealDictCursor

# Connection parameters
conn = psycopg2.connect(
    host='pg-service.aivencloud.com',
    port=12345,
    dbname='defaultdb',
    user='avnadmin',
    password='your-password',
    sslmode='require'
)

# Execute query
with conn.cursor(cursor_factory=RealDictCursor) as cur:
    cur.execute("SELECT version();")
    result = cur.fetchone()
    print(result['version'])

# Insert data
with conn.cursor() as cur:
    cur.execute(
        "INSERT INTO users (email, name) VALUES (%s, %s)",
        ('[email protected]', 'John Doe')
    )
    conn.commit()

conn.close()
Using SQLAlchemy:
from sqlalchemy import create_engine, text

engine = create_engine(
    'postgresql://avnadmin:[email protected]:12345/defaultdb?sslmode=require'
)

with engine.connect() as conn:
    result = conn.execute(text("SELECT * FROM users"))
    for row in result:
        print(row)

High Availability

Aiven for PostgreSQL provides multiple levels of availability:
1 Primary + 1 Standby Node
  • Synchronous replication to standby
  • Automatic failover in case of primary failure
  • Read replicas for read scaling
  • 14 days backup retention
  • 99.99% SLA
Failure Handling:
  • Primary fails → Standby promoted automatically
  • Standby fails → Primary continues serving
  • Service URI remains constant (only IP changes)

Performance Optimization

Choose the right index type for your queries:
-- B-tree (default) - most common
CREATE INDEX idx_email ON users(email);

-- GiST for full-text search
CREATE INDEX idx_content_search ON articles USING GiST(to_tsvector('english', content));

-- GIN for JSONB and arrays
CREATE INDEX idx_metadata ON products USING GIN(metadata);

-- BRIN for large time-series tables
CREATE INDEX idx_created_at ON events USING BRIN(created_at);

-- Partial index for specific conditions
CREATE INDEX idx_active_users ON users(email) WHERE active = true;
Use EXPLAIN ANALYZE to optimize queries:
-- Analyze query performance
EXPLAIN (ANALYZE, BUFFERS) 
SELECT * FROM users WHERE email LIKE '%@example.com';

-- Use pg_stat_statements for query stats
SELECT query, calls, mean_exec_time, total_exec_time
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;
Configure PgBouncer for optimal connection management:
  • Session mode: For applications that need session-level features
  • Transaction mode: Best for most web applications
  • Statement mode: Maximum connection reuse
Update via Aiven Console or API:
avn service update my-pg \
  -c pgbouncer.pool_mode=transaction \
  -c pgbouncer.max_client_conn=1000
PostgreSQL automatically tunes shared_buffers based on available memory:
  • Business-4: 1 GB shared_buffers
  • Business-8: 2 GB shared_buffers
  • Business-16: 4 GB shared_buffers
Monitor buffer usage:
SELECT * FROM pg_stat_bgwriter;

Backup and Recovery

Automatic Backups

  • Continuous WAL archiving
  • Point-in-time recovery (PITR)
  • Encrypted backups in object storage
  • Retention: 2-30 days based on plan

Manual Backups

  • On-demand backup creation
  • Fork services from backups
  • Export backups for migration
  • Cross-region backup storage
Restore to Point in Time:
avn service update my-pg \
  --restore-point-in-time "2024-03-04T10:30:00Z"
Fork a Service:
avn service create my-pg-fork \
  --service-type pg \
  --cloud aws-us-east-1 \
  --plan business-4 \
  --fork-from my-pg

Monitoring and Observability

Key Metrics

  • Connections: Active and idle connections
  • Transactions per second: Database throughput
  • Cache hit ratio: Buffer efficiency (target >99%)
  • Query latency: Average query execution time
  • Replication lag: Delay between primary and standby

Integration with Aiven Services

avn service integration-create \
  --integration-type metrics \
  --source-service my-pg \
  --dest-service my-grafana

Security Best Practices

  • Use strong passwords for database users
  • Implement least-privilege access control
  • Create separate users for applications
  • Use certificate authentication where possible
  • Rotate credentials regularly
-- Create read-only user
CREATE USER readonly_user WITH PASSWORD 'strong_password';
GRANT CONNECT ON DATABASE myapp TO readonly_user;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly_user;
  • Enable VPC peering for private connectivity
  • Use IP allowlisting to restrict access
  • Configure AWS PrivateLink for secure connections
  • Always use SSL/TLS connections
  • Implement application-level encryption for sensitive data
Enable pgaudit for compliance:
CREATE EXTENSION pgaudit;

-- Audit all DDL and DCL statements
ALTER SYSTEM SET pgaudit.log = 'ddl, role';

-- Audit specific tables
ALTER TABLE sensitive_data SET (pgaudit.log = 'read, write');

Use Cases

Traditional web apps with transactional data:
  • E-commerce platforms
  • Content management systems
  • User authentication and profiles
  • Session storage

Migration to Aiven

1

Prepare Source Database

  • Document current schema and extensions
  • Identify custom configurations
  • Plan for minimal downtime
2

Use aiven-db-migrate

Built-in migration tool for PostgreSQL:
avn service migration-start my-pg \
  --source-host source-db.example.com \
  --source-port 5432 \
  --source-username postgres \
  --source-password xxx \
  --source-dbname mydb
3

Verify Migration

  • Check row counts
  • Verify indexes and constraints
  • Test application connectivity
  • Monitor replication lag
4

Cutover

  • Stop writes to source
  • Wait for replication to complete
  • Update application connection strings
  • Verify application functionality

Apache Kafka

Stream changes with Debezium CDC to Kafka

Apache Flink

Real-time processing with Flink PostgreSQL connector

Grafana

Visualize PostgreSQL data and metrics

OpenSearch

Full-text search with PostgreSQL data

Resources

Migration Support: Aiven provides free migration assistance for Enterprise customers. Contact support for help migrating your PostgreSQL databases.

Build docs developers (and LLMs) love