Skip to main content
Aiven for MySQL is a fully managed relational database service that provides a reliable, scalable MySQL platform for your applications. Available from single-node starter plans to highly available production clusters with automated backups and monitoring.

Overview

MySQL has been a cornerstone of the open-source database landscape for decades, powering millions of applications worldwide. Aiven for MySQL provides the reliability and features you expect from MySQL, with the added benefits of fully managed operations, automated backups, and enterprise-grade security.

Why Choose Aiven for MySQL

Fully Managed

Automated backups, updates, monitoring, and maintenance with zero downtime

High Availability

Multi-node replication with automatic failover for business continuity

MyHoard Backups

Aiven’s open-source backup and restore tool for MySQL with point-in-time recovery

Remote Replicas

Create read replicas across regions for disaster recovery and read scaling

Key Features

Aiven for MySQL provides automatic replication and failover:Single-Node Plans (Hobbyist/Startup):
  • Development and testing
  • Cost-effective for non-critical workloads
  • Automatic backups and restore
Multi-Node Plans (Business/Premium):
  • Primary-replica replication
  • Automatic failover on primary failure
  • Read replicas for scaling reads
  • Synchronous replication options
Aiven’s open-source backup solution for MySQL:
  • Continuous binary log streaming
  • Point-in-time recovery (PITR)
  • Encrypted backups in object storage
  • Fast restoration from backups
  • Cross-region backup storage
Backup Retention:
  • Hobbyist/Startup: 2 days
  • Business: 14 days
  • Premium: 30 days
Create read replicas in different regions:
  • Reduce read latency for global users
  • Disaster recovery standby
  • Cross-region data distribution
  • Promote replica to primary if needed
avn service create my-mysql-replica \
  --service-type mysql \
  --cloud aws-eu-west-1 \
  --plan business-4 \
  --replica-of my-mysql-primary
Automatic tuning based on workload:
  • InnoDB buffer pool sizing
  • Connection pool management
  • Query cache configuration
  • Slow query logging
  • Performance schema enabled

Getting Started

1

Create MySQL Service

Deploy a MySQL service using Aiven Console, CLI, or API:
avn service create my-mysql \
  --service-type mysql \
  --cloud aws-us-east-1 \
  --plan business-4 \
  --mysql-version 8.0
Available MySQL Versions: 8.0 (recommended)
2

Create Database and Tables

Connect and create your database schema:
mysql -h mysql-service.aivencloud.com \
  -P 12345 \
  -u avnadmin \
  -p \
  --ssl-mode=REQUIRED
CREATE DATABASE myapp;
USE myapp;

CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  email VARCHAR(255) UNIQUE NOT NULL,
  name VARCHAR(255),
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_email (email)
);
3

Configure Application

Use connection details from service overview to connect your application with SSL enabled.

Connection Examples

import pymysql
import ssl

# Create SSL context
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_REQUIRED
ssl_context.load_verify_locations('ca.pem')

# Connect to MySQL
connection = pymysql.connect(
    host='mysql-service.aivencloud.com',
    port=12345,
    user='avnadmin',
    password='your-password',
    database='defaultdb',
    ssl=ssl_context
)

try:
    with connection.cursor() as cursor:
        # Create table
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS tasks (
                id INT AUTO_INCREMENT PRIMARY KEY,
                title VARCHAR(255) NOT NULL,
                completed BOOLEAN DEFAULT FALSE
            )
        """)
        
        # Insert data
        cursor.execute(
            "INSERT INTO tasks (title) VALUES (%s), (%s)",
            ('Task 1', 'Task 2')
        )
        connection.commit()
        
        # Query data
        cursor.execute("SELECT * FROM tasks")
        results = cursor.fetchall()
        for row in results:
            print(row)
finally:
    connection.close()
Using SQLAlchemy:
from sqlalchemy import create_engine, text

engine = create_engine(
    'mysql+pymysql://avnadmin:[email protected]:12345/defaultdb?ssl_ca=ca.pem'
)

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

Performance Tuning

Optimize connection handling:
  • Use connection pooling in your application
  • Set appropriate max_connections for your workload
  • Monitor active connections: SHOW PROCESSLIST
  • Configure wait_timeout and interactive_timeout
-- Check current connection count
SHOW STATUS LIKE 'Threads_connected';

-- View max connections setting
SHOW VARIABLES LIKE 'max_connections';
Create effective indexes:
-- Add index for frequently queried columns
CREATE INDEX idx_user_email ON users(email);

-- Composite index for multi-column queries
CREATE INDEX idx_user_status_created ON users(status, created_at);

-- Full-text search index
CREATE FULLTEXT INDEX idx_content ON articles(title, content);

-- Check index usage
SHOW INDEX FROM users;
Identify and optimize slow queries:
-- Enable slow query log
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 1;

-- Analyze query performance
EXPLAIN SELECT * FROM users WHERE email LIKE '%@example.com';

-- View slow queries
SELECT * FROM mysql.slow_log ORDER BY query_time DESC LIMIT 10;
MySQL automatically tunes memory based on your plan:
  • InnoDB buffer pool (largest memory consumer)
  • Query cache (for repeated queries)
  • Sort buffer and join buffer
  • Connection buffers
-- Check buffer pool usage
SHOW STATUS LIKE 'Innodb_buffer_pool%';

High Availability and Replication

Business and Premium plans include automatic failover:
  • Primary node handles all writes
  • Replica nodes synchronize continuously
  • Automatic promotion on primary failure
  • Service URI remains constant
  • Typical failover time: 1-2 minutes
Monitoring Replication:
SHOW REPLICA STATUS\G

Monitoring and Troubleshooting

Key Metrics to Monitor

Connection Metrics

  • Active connections
  • Connection errors
  • Max connections reached
  • Aborted connections

Query Performance

  • Queries per second
  • Slow query count
  • Average query time
  • Query cache hit rate

Replication

  • Replication lag
  • Replica IO/SQL thread status
  • Binary log position
  • Replica errors

Resource Usage

  • CPU utilization
  • Memory usage
  • Disk I/O
  • Disk space available

Troubleshooting Common Issues

-- Check current connections
SELECT COUNT(*) FROM information_schema.PROCESSLIST;

-- Kill idle connections
SELECT CONCAT('KILL ', id, ';') 
FROM information_schema.PROCESSLIST 
WHERE command = 'Sleep' 
AND time > 300;
-- Find queries without indexes
SELECT * FROM sys.statements_with_full_table_scans;

-- Identify missing indexes
SELECT * FROM sys.schema_unused_indexes;
-- Check replication status
SHOW REPLICA STATUS\G

-- Monitor seconds behind master
SELECT Seconds_Behind_Master 
FROM performance_schema.replication_connection_status;

Security Best Practices

Create users with appropriate privileges:
-- Create application user
CREATE USER 'app_user'@'%' IDENTIFIED BY 'strong_password';

-- Grant specific privileges
GRANT SELECT, INSERT, UPDATE, DELETE ON myapp.* TO 'app_user'@'%';

-- Create read-only user
CREATE USER 'readonly'@'%' IDENTIFIED BY 'strong_password';
GRANT SELECT ON myapp.* TO 'readonly'@'%';

-- Apply changes
FLUSH PRIVILEGES;
Always use encrypted connections:
  • Aiven requires SSL by default
  • Download CA certificate from console
  • Configure clients with --ssl-mode=REQUIRED
  • Verify server certificate
  • Enable VPC peering for private access
  • Use IP allowlisting to restrict access
  • Configure AWS PrivateLink
  • Implement application-level encryption for sensitive data

Migration to Aiven

1

Prepare Source Database

  • Ensure MySQL version compatibility (5.7 or 8.0)
  • Note custom configurations
  • Plan maintenance window
2

Export Data

mysqldump -h source-host \
  -u root \
  -p \
  --single-transaction \
  --routines \
  --triggers \
  --all-databases > backup.sql
3

Import to Aiven

mysql -h mysql-service.aivencloud.com \
  -P 12345 \
  -u avnadmin \
  -p \
  --ssl-mode=REQUIRED \
  < backup.sql
4

Verify and Test

  • Compare row counts
  • Test application connectivity
  • Verify all tables and indexes
  • Check stored procedures and triggers

Use Cases

  • E-commerce platforms
  • Content management systems
  • Blog platforms (WordPress, Drupal)
  • User authentication systems

Apache Kafka

Stream database changes with Debezium CDC

Grafana

Visualize MySQL metrics and data

ClickHouse

Replicate to ClickHouse for analytics

Apache Flink

Real-time processing with MySQL connector

Resources

Primary Keys Required: Aiven for MySQL requires primary keys on all tables for replication. Learn how to create missing primary keys.

Build docs developers (and LLMs) love