Overview
Cloud deployment models define the location, ownership, and access characteristics of cloud computing infrastructure. Each model represents a distinct approach to provisioning computational resources, storage, and networking capabilities. The choice of deployment model affects application architecture, operational costs, security posture, compliance requirements, and scaling capabilities.
Four primary deployment models exist: public cloud, private cloud, hybrid cloud, and community cloud. A fifth category, multi-cloud, represents the use of multiple cloud providers simultaneously. Each model serves different organizational needs based on control requirements, budget constraints, regulatory compliance, and technical specifications.
Public cloud infrastructure runs on shared hardware managed by third-party providers like AWS, Google Cloud, or Azure. Organizations consume resources on-demand without maintaining physical infrastructure. Private cloud dedicates infrastructure exclusively to a single organization, either on-premises or hosted by a third party. Hybrid cloud combines public and private elements, enabling workload distribution across environments. Community cloud shares infrastructure among organizations with common requirements, such as regulatory compliance or industry standards.
The deployment model selection impacts development workflows, deployment pipelines, infrastructure management, and application design. Ruby applications adapt to different deployment models through configuration management, environment-specific dependencies, and cloud provider SDKs. The model choice influences database selection, caching strategies, session management, and background job processing.
# Cloud deployment configuration in a Ruby application
# config/cloud.yml
production:
deployment_model: "hybrid"
primary_region: "us-east-1"
failover_region: "us-west-2"
private_services:
- "database"
- "message_queue"
public_services:
- "web_application"
- "api"
- "cdn"
Understanding deployment models helps architects make informed infrastructure decisions. Each model presents trade-offs between cost, control, security, compliance, and operational complexity. Organizations frequently start with public cloud for speed and cost efficiency, then evolve toward hybrid or multi-cloud as requirements mature.
Key Principles
Cloud deployment models operate on fundamental principles of resource allocation, infrastructure ownership, network access, and management responsibility. These principles determine how applications interact with underlying infrastructure and how organizations maintain control over their computing environment.
Resource Isolation and Sharing
Public cloud shares physical infrastructure across multiple tenants through virtualization and containerization. Hypervisors and orchestration platforms create logical boundaries between workloads. Private cloud dedicates resources to a single tenant, eliminating noisy neighbor problems and providing predictable performance. Hybrid cloud selectively shares or isolates resources based on workload characteristics.
Resource sharing affects performance predictability, security isolation, and cost structure. Shared infrastructure reduces per-unit costs through economy of scale but introduces variability in performance. Dedicated infrastructure provides consistent performance at higher cost. The isolation model influences application design decisions around caching, database connection pooling, and background job processing.
Infrastructure Ownership and Control
Public cloud providers own and operate physical infrastructure, network equipment, and data centers. Organizations consume services without capital expenditure on hardware. Private cloud shifts ownership to the organization or a dedicated hosting provider. This ownership model affects upgrade cycles, hardware refresh schedules, and capacity planning responsibilities.
Control extends beyond hardware to include network configuration, security policies, and compliance frameworks. Private cloud grants complete control over network topology, firewall rules, and data residency. Public cloud offers configuration options within provider-defined boundaries. Hybrid cloud requires coordinating control across environments, managing consistent policies, and synchronizing security configurations.
# Infrastructure provider abstraction in Ruby
class InfrastructureProvider
def initialize(deployment_model:, provider:)
@deployment_model = deployment_model
@provider = provider
end
def provision_resources(specs)
case @deployment_model
when :public
@provider.create_instances(specs, shared: true)
when :private
@provider.create_instances(specs, shared: false, dedicated_tenant: true)
when :hybrid
distribute_workload(specs)
end
end
private
def distribute_workload(specs)
sensitive_workloads = specs.select { |s| s[:data_classification] == :sensitive }
general_workloads = specs.reject { |s| s[:data_classification] == :sensitive }
@provider.create_instances(sensitive_workloads, environment: :private)
@provider.create_instances(general_workloads, environment: :public)
end
end
Network Access Models
Public cloud services typically expose endpoints over the public internet, protected by authentication and encryption. Private cloud operates on isolated networks with restricted access. Hybrid cloud requires secure connectivity between environments through VPN tunnels, dedicated circuits, or SD-WAN solutions.
Network access affects application design for authentication, authorization, and data transfer. Public cloud applications implement robust authentication mechanisms and encrypt data in transit. Private cloud applications may rely on network-level security controls. Hybrid applications manage authentication across environments and handle network latency between cloud segments.
Service Management Responsibility
The deployment model determines the division of management responsibilities between provider and consumer. Public cloud follows a shared responsibility model where providers manage infrastructure layers while consumers manage application layers. Private cloud places full management responsibility on the organization. Hybrid cloud requires managing both owned infrastructure and consumed services.
Management responsibilities include patching, monitoring, backup, disaster recovery, and capacity planning. Public cloud automates many infrastructure tasks, reducing operational overhead. Private cloud requires dedicated operations teams. The responsibility model influences staffing requirements, operational processes, and incident response procedures.
Data Residency and Sovereignty
Deployment models affect data location and jurisdictional control. Public cloud providers operate data centers globally, storing data based on region selection. Private cloud keeps data within organization-controlled facilities. Hybrid cloud distributes data across environments based on classification and regulatory requirements.
Data residency impacts compliance with regulations like GDPR, HIPAA, or financial services requirements. Organizations must ensure data placement aligns with legal obligations. The deployment model choice directly affects ability to meet data sovereignty requirements and maintain audit trails for data access.
Implementation Approaches
Implementing cloud deployment models requires strategic planning for infrastructure provisioning, application architecture, and operational processes. Different approaches suit different organizational maturity levels, technical requirements, and business objectives.
Public Cloud Implementation
Public cloud implementation begins with selecting a primary provider based on service offerings, regional availability, and pricing models. Organizations establish identity and access management, configure networking with VPCs and subnets, and define security groups. Applications deploy through provider-specific tools or generic deployment platforms.
The infrastructure-as-code approach treats infrastructure configuration as versioned code. Tools like Terraform, CloudFormation, or Pulumi define resources declaratively. This approach enables reproducible deployments, version control for infrastructure changes, and automated provisioning pipelines.
# Ruby application deployment configuration for public cloud
# deploy/aws_config.rb
require 'aws-sdk-ec2'
require 'aws-sdk-rds'
class AWSDeployment
def initialize(region:, environment:)
@ec2 = Aws::EC2::Client.new(region: region)
@rds = Aws::RDS::Client.new(region: region)
@environment = environment
end
def deploy_application(config)
vpc_id = create_vpc(config[:vpc_cidr])
subnet_ids = create_subnets(vpc_id, config[:subnet_cidrs])
security_group_id = create_security_group(vpc_id, config[:security_rules])
db_instance = provision_database(
subnet_ids: subnet_ids,
security_group_id: security_group_id,
instance_class: config[:db_instance_class]
)
app_servers = provision_app_servers(
subnet_ids: subnet_ids,
security_group_id: security_group_id,
instance_type: config[:app_instance_type],
count: config[:instance_count]
)
configure_load_balancer(app_servers, security_group_id)
end
private
def create_vpc(cidr_block)
resp = @ec2.create_vpc(cidr_block: cidr_block)
resp.vpc.vpc_id
end
def provision_database(subnet_ids:, security_group_id:, instance_class:)
subnet_group = @rds.create_db_subnet_group(
db_subnet_group_name: "#{@environment}-subnet-group",
subnet_ids: subnet_ids
)
@rds.create_db_instance(
db_instance_identifier: "#{@environment}-postgres",
engine: 'postgres',
engine_version: '15.3',
db_instance_class: instance_class,
allocated_storage: 100,
vpc_security_group_ids: [security_group_id],
db_subnet_group_name: subnet_group.db_subnet_group.db_subnet_group_name
)
end
end
Container-based deployment packages applications with dependencies into Docker images. Orchestration platforms like Kubernetes or ECS manage container lifecycle, scaling, and health checks. This approach provides environment consistency and simplifies dependency management.
Serverless deployment eliminates infrastructure management by running code in response to events. Functions execute in managed runtimes, scaling automatically based on demand. This approach suits event-driven workloads, API backends, and data processing pipelines.
Private Cloud Implementation
Private cloud implementation requires provisioning physical infrastructure, installing virtualization platforms, and configuring management tools. Organizations deploy OpenStack, VMware vSphere, or Microsoft Azure Stack for infrastructure management. The implementation includes network configuration, storage provisioning, and compute resource allocation.
On-premises private cloud provides maximum control but requires capital investment in hardware, facilities, and operations staff. Hosted private cloud delegates infrastructure management to providers while maintaining dedicated resources. The hosted approach reduces capital expenditure while preserving control over configuration and access.
# Private cloud infrastructure management with OpenStack SDK
require 'fog/openstack'
class PrivateCloudManager
def initialize(auth_url:, tenant:, username:, password:)
@compute = Fog::Compute.new(
provider: 'openstack',
openstack_auth_url: auth_url,
openstack_tenant: tenant,
openstack_username: username,
openstack_api_key: password
)
end
def provision_instance(name:, flavor:, image:, network:)
server = @compute.servers.create(
name: name,
flavor_ref: find_flavor_id(flavor),
image_ref: find_image_id(image),
nics: [{ net_id: find_network_id(network) }]
)
server.wait_for { ready? }
configure_instance(server)
server
end
def configure_instance(server)
# Apply security hardening
server.associate_address(allocate_floating_ip)
apply_security_policies(server)
install_monitoring_agent(server)
end
private
def find_flavor_id(flavor_name)
@compute.flavors.find { |f| f.name == flavor_name }&.id
end
end
Hybrid Cloud Implementation
Hybrid cloud implementation connects public and private environments through network integration, identity federation, and data synchronization. Organizations establish VPN connections, direct connect circuits, or SD-WAN for secure communication between environments. Identity providers federate authentication across cloud boundaries.
Workload placement strategy determines which applications run in each environment. Sensitive data processing and regulated workloads typically remain in private cloud. Customer-facing applications and variable workloads deploy to public cloud. The placement strategy balances security requirements, compliance constraints, and cost optimization.
Data synchronization maintains consistency across environments. Replication mechanisms copy data between cloud segments based on latency requirements and consistency models. Database replication, object storage sync, and message queues coordinate state across environments.
# Hybrid cloud workload orchestrator
class HybridOrchestrator
def initialize(public_provider:, private_provider:)
@public = public_provider
@private = private_provider
end
def deploy_workload(application_config)
workload_classification = classify_workload(application_config)
case workload_classification
when :sensitive
deploy_to_private_cloud(application_config)
when :public_facing
deploy_to_public_cloud(application_config)
when :distributed
deploy_hybrid_architecture(application_config)
end
end
private
def classify_workload(config)
return :sensitive if config[:data_classification] == :pii
return :sensitive if config[:compliance_requirements].include?(:hipaa)
return :public_facing if config[:internet_facing] && !config[:sensitive_data]
:distributed
end
def deploy_hybrid_architecture(config)
# Deploy data tier to private cloud
private_services = @private.provision_resources([
{ type: :database, specs: config[:database] },
{ type: :cache, specs: config[:cache] }
])
# Deploy application tier to public cloud
public_services = @public.provision_resources([
{ type: :web_server, specs: config[:web_servers] },
{ type: :load_balancer, specs: config[:load_balancer] }
])
# Configure cross-environment connectivity
establish_vpn_tunnel(private_services, public_services)
configure_service_mesh(private_services + public_services)
end
end
Multi-Cloud Implementation
Multi-cloud implementation distributes workloads across multiple public cloud providers. Organizations select providers based on regional presence, specific services, or redundancy requirements. The implementation requires abstraction layers to manage provider differences and prevent vendor lock-in.
Service mesh architectures provide consistent networking, observability, and security across providers. Control planes coordinate traffic routing, policy enforcement, and service discovery. Data planes handle actual workload communication.
Container orchestration with Kubernetes offers portable workload definitions across providers. Cluster federation manages applications spanning multiple Kubernetes clusters. This approach standardizes deployment processes and enables workload mobility.
Design Considerations
Selecting a cloud deployment model requires evaluating technical requirements, business constraints, and operational capabilities. The decision affects application architecture, development processes, operational costs, and long-term flexibility.
Cost Structure Analysis
Public cloud operates on operational expenditure with pay-per-use pricing. Organizations pay for consumed resources without upfront hardware investment. Variable workloads benefit from elastic scaling, paying only for active capacity. Steady-state workloads may incur higher costs compared to owned infrastructure due to provider margins.
Private cloud requires capital expenditure for hardware, facilities, and network equipment. Operational expenses include power, cooling, maintenance, and staff salaries. The break-even point typically occurs at sustained high utilization levels. Organizations must forecast capacity requirements and plan for growth.
Hybrid cloud balances capital and operational expenditure by placing baseline workloads on private infrastructure and burst capacity on public cloud. This approach optimizes cost for predictable workloads with occasional spikes. Multi-cloud introduces complexity costs through additional management overhead and integration challenges.
Security and Compliance Requirements
Regulatory compliance influences deployment model selection. HIPAA, PCI DSS, and financial services regulations impose strict controls on data access, encryption, and audit trails. Private cloud offers maximum control for meeting compliance requirements through dedicated infrastructure and customized security controls.
Public cloud providers offer compliance certifications and frameworks but share infrastructure across tenants. Organizations must evaluate whether shared responsibility models satisfy regulatory obligations. Certain regulations mandate data residency in specific geographic locations, limiting provider and region selection.
Hybrid cloud enables compliance by classification, keeping regulated data in private cloud while using public cloud for non-sensitive workloads. This approach requires robust data classification processes and automated enforcement of placement policies.
Performance and Latency Requirements
Network latency between application components affects user experience and system performance. Public cloud data centers concentrate in specific regions, potentially distant from end users or data sources. Private cloud locates close to organizational facilities, minimizing latency for internal applications.
Hybrid cloud introduces latency between cloud segments. Applications requiring tight coupling between components may experience degraded performance when split across environments. Careful workload placement and asynchronous communication patterns mitigate latency impacts.
Multi-cloud enables geographic distribution for reduced latency to global users. Applications deploy close to customer populations using regional providers. This approach requires sophisticated traffic routing and data replication strategies.
Control and Customization Needs
Private cloud provides complete control over infrastructure configuration, network topology, and security policies. Organizations customize virtualization platforms, storage configurations, and network architecture to exact specifications. This control suits organizations with unique requirements or deep infrastructure expertise.
Public cloud offers configuration within provider-defined parameters. Networking, security, and service options follow provider architectures. Organizations sacrifice customization for reduced operational complexity and faster deployment.
The control trade-off extends to software versions, patching schedules, and technology selection. Private cloud permits running legacy software versions indefinitely. Public cloud enforces regular updates and deprecates outdated services.
Operational Maturity and Expertise
Private cloud requires infrastructure operations expertise including virtualization, networking, storage, and capacity planning. Organizations must staff operations teams, establish monitoring systems, and develop runbooks for incident response. This operational burden suits organizations with existing infrastructure teams and operations experience.
Public cloud reduces infrastructure expertise requirements by delegating hardware management to providers. Organizations focus on application operations rather than infrastructure maintenance. This model accelerates adoption for development-focused organizations.
Hybrid and multi-cloud multiply operational complexity through heterogeneous environments. Organizations require expertise across multiple platforms and tools. Successful implementation demands strong automation practices and infrastructure-as-code discipline.
Ruby Implementation
Ruby applications adapt to different cloud deployment models through configuration management, environment-specific dependencies, and provider SDKs. The implementation approach depends on deployment model characteristics and application architecture requirements.
Cloud Provider Integration
Ruby applications integrate with cloud providers through official SDKs. AWS SDK for Ruby, Google Cloud Client Libraries, and Azure SDK provide native interfaces to cloud services. These libraries handle authentication, request signing, and API communication.
# Multi-provider cloud storage abstraction
require 'aws-sdk-s3'
require 'google/cloud/storage'
class CloudStorageAdapter
def initialize(provider:, credentials:)
@provider = provider
@client = initialize_client(provider, credentials)
end
def upload_file(bucket:, key:, file_path:)
case @provider
when :aws
upload_to_s3(bucket, key, file_path)
when :gcp
upload_to_gcs(bucket, key, file_path)
when :private
upload_to_private_storage(bucket, key, file_path)
end
end
def download_file(bucket:, key:)
case @provider
when :aws
download_from_s3(bucket, key)
when :gcp
download_from_gcs(bucket, key)
when :private
download_from_private_storage(bucket, key)
end
end
private
def initialize_client(provider, credentials)
case provider
when :aws
Aws::S3::Client.new(
region: credentials[:region],
access_key_id: credentials[:access_key],
secret_access_key: credentials[:secret_key]
)
when :gcp
Google::Cloud::Storage.new(
project_id: credentials[:project_id],
credentials: credentials[:service_account_path]
)
when :private
# Private cloud storage client (e.g., MinIO, Ceph)
initialize_private_client(credentials)
end
end
def upload_to_s3(bucket, key, file_path)
File.open(file_path, 'rb') do |file|
@client.put_object(
bucket: bucket,
key: key,
body: file,
server_side_encryption: 'AES256'
)
end
end
def upload_to_gcs(bucket, key, file_path)
bucket_obj = @client.bucket(bucket)
bucket_obj.create_file(file_path, key)
end
end
Environment-Specific Configuration
Ruby applications manage deployment model variations through environment-specific configuration. The config gem or Rails credentials encrypt sensitive configuration values. Environment variables override defaults for different deployment targets.
# config/environments/production.rb
Rails.application.configure do
# Cloud deployment model configuration
config.cloud_provider = ENV.fetch('CLOUD_PROVIDER', 'aws')
config.deployment_model = ENV.fetch('DEPLOYMENT_MODEL', 'public')
# Storage configuration based on deployment model
config.active_storage.service = case config.deployment_model
when 'public'
:amazon
when 'private'
:private_s3
when 'hybrid'
:hybrid_storage
else
:local
end
# Cache configuration
config.cache_store = if config.deployment_model == 'private'
:redis_cache_store, {
url: ENV['PRIVATE_REDIS_URL'],
pool_size: ENV.fetch('RAILS_MAX_THREADS', 5).to_i
}
else
:mem_cache_store, ENV['MEMCACHED_SERVERS']&.split(',')
end
# Database configuration
if config.deployment_model == 'hybrid'
# Use private cloud for primary database
config.primary_database_url = ENV['PRIVATE_DB_URL']
# Use public cloud for read replicas
config.read_replica_urls = ENV['PUBLIC_REPLICA_URLS']&.split(',')
end
end
Service Discovery and Registration
Applications in distributed cloud environments require service discovery to locate dependencies. Consul, etcd, or cloud-native service registries track service locations across environments. Ruby applications query registries to find service endpoints dynamically.
# Service discovery for hybrid cloud environments
require 'diplomat'
class ServiceRegistry
def initialize(consul_url:)
Diplomat.configure do |config|
config.url = consul_url
end
end
def register_service(name:, address:, port:, environment:)
Diplomat::Service.register(
{
name: name,
address: address,
port: port,
tags: [environment, deployment_model],
check: {
http: "http://#{address}:#{port}/health",
interval: "10s"
}
}
)
end
def discover_service(name:, environment:)
services = Diplomat::Service.get(name, :all)
services.select { |s| s.ServiceTags.include?(environment) }
end
def get_database_endpoint(environment:)
case deployment_model
when :public
discover_service(name: 'postgres', environment: environment).first
when :private
{ address: ENV['PRIVATE_DB_HOST'], port: 5432 }
when :hybrid
# Primary database in private cloud
primary = { address: ENV['PRIVATE_DB_HOST'], port: 5432 }
# Read replicas in public cloud
replicas = discover_service(name: 'postgres-replica', environment: environment)
{ primary: primary, replicas: replicas }
end
end
private
def deployment_model
ENV.fetch('DEPLOYMENT_MODEL', 'public').to_sym
end
end
Cross-Environment Communication
Hybrid and multi-cloud deployments require secure communication between environments. Ruby applications establish VPN tunnels, use TLS for service-to-service communication, and implement mutual authentication.
# Secure service client for hybrid cloud communication
require 'faraday'
require 'openssl'
class SecureServiceClient
def initialize(service_name:, environment:, registry:)
@service_name = service_name
@environment = environment
@registry = registry
end
def call_service(endpoint:, payload:)
service_info = @registry.discover_service(
name: @service_name,
environment: @environment
).first
connection = build_connection(service_info)
response = connection.post(endpoint) do |req|
req.headers['Content-Type'] = 'application/json'
req.headers['X-API-Key'] = api_key
req.body = payload.to_json
end
JSON.parse(response.body)
end
private
def build_connection(service_info)
Faraday.new(url: service_url(service_info)) do |conn|
# Mutual TLS for cross-environment communication
conn.ssl.client_cert = load_certificate
conn.ssl.client_key = load_private_key
conn.ssl.ca_file = load_ca_bundle
conn.ssl.verify = true
# Connection pooling
conn.adapter Faraday.default_adapter
end
end
def service_url(service_info)
"https://#{service_info[:address]}:#{service_info[:port]}"
end
def load_certificate
cert_path = Rails.root.join('config', 'certs', "#{@environment}.crt")
OpenSSL::X509::Certificate.new(File.read(cert_path))
end
def load_private_key
key_path = Rails.root.join('config', 'certs', "#{@environment}.key")
OpenSSL::PKey::RSA.new(File.read(key_path))
end
end
Database Connection Management
Ruby applications handle database connections differently across deployment models. Public cloud emphasizes connection pooling and automatic failover. Private cloud may use persistent connections with manual failover. Hybrid cloud distributes read and write operations across environments.
# Database connection strategy for different deployment models
class DatabaseConnectionManager
def initialize(deployment_model:)
@deployment_model = deployment_model
end
def configure_connections
case @deployment_model
when :public
configure_public_cloud_database
when :private
configure_private_cloud_database
when :hybrid
configure_hybrid_cloud_database
end
end
private
def configure_public_cloud_database
# Use connection pooling for public cloud RDS
ActiveRecord::Base.establish_connection(
adapter: 'postgresql',
host: ENV['RDS_ENDPOINT'],
database: ENV['RDS_DATABASE'],
username: ENV['RDS_USERNAME'],
password: ENV['RDS_PASSWORD'],
pool: ENV.fetch('DB_POOL_SIZE', 25).to_i,
checkout_timeout: 5,
# Enable automatic retry for transient failures
retry_deadline: 3,
connect_timeout: 2
)
end
def configure_private_cloud_database
# Direct connection to private database cluster
ActiveRecord::Base.establish_connection(
adapter: 'postgresql',
host: ENV['PRIVATE_DB_HOST'],
port: ENV.fetch('PRIVATE_DB_PORT', 5432),
database: ENV['PRIVATE_DB_NAME'],
username: ENV['PRIVATE_DB_USERNAME'],
password: ENV['PRIVATE_DB_PASSWORD'],
pool: ENV.fetch('DB_POOL_SIZE', 10).to_i
)
end
def configure_hybrid_cloud_database
# Primary database in private cloud
primary_config = {
adapter: 'postgresql',
host: ENV['PRIVATE_DB_HOST'],
database: ENV['DB_NAME'],
username: ENV['PRIVATE_DB_USERNAME'],
password: ENV['PRIVATE_DB_PASSWORD'],
pool: 15
}
# Read replicas in public cloud
replica_config = {
adapter: 'postgresql',
host: ENV['PUBLIC_REPLICA_HOST'],
database: ENV['DB_NAME'],
username: ENV['PUBLIC_DB_USERNAME'],
password: ENV['PUBLIC_DB_PASSWORD'],
replica: true,
pool: 20
}
ActiveRecord::Base.configurations = {
'production' => primary_config,
'production_replica' => replica_config
}
ActiveRecord::Base.establish_connection(:production)
end
end
Tools & Ecosystem
Cloud deployment model implementation relies on infrastructure management tools, deployment automation platforms, and monitoring systems. Ruby ecosystem provides gems and frameworks that integrate with cloud providers and deployment platforms.
Infrastructure as Code Tools
Terraform enables multi-cloud infrastructure provisioning through declarative configuration. The tool manages resources across AWS, GCP, Azure, and private cloud platforms. State files track infrastructure state, enabling incremental updates and drift detection.
# Ruby wrapper for Terraform operations
require 'open3'
require 'json'
class TerraformManager
def initialize(working_directory:)
@working_directory = working_directory
end
def plan(var_file:)
execute_command("terraform plan -var-file=#{var_file} -out=tfplan")
end
def apply
execute_command("terraform apply tfplan")
end
def destroy(var_file:)
execute_command("terraform destroy -var-file=#{var_file} -auto-approve")
end
def output(name)
stdout, status = execute_command("terraform output -json #{name}")
JSON.parse(stdout) if status.success?
end
private
def execute_command(command)
stdout, stderr, status = Open3.capture3(
command,
chdir: @working_directory
)
raise "Terraform error: #{stderr}" unless status.success?
[stdout, status]
end
end
# Usage in deployment script
terraform = TerraformManager.new(
working_directory: Rails.root.join('terraform', ENV['DEPLOYMENT_MODEL'])
)
terraform.plan(var_file: "environments/#{Rails.env}.tfvars")
terraform.apply
CloudFormation manages AWS infrastructure through JSON or YAML templates. The AWS SDK for Ruby provides programmatic access to CloudFormation operations, enabling automated stack creation and updates.
Pulumi uses programming languages including Ruby for infrastructure definition. This approach provides type safety, IDE support, and familiar programming constructs for infrastructure management.
Container Orchestration
Docker packages Ruby applications with dependencies into portable container images. Dockerfile defines build steps, base images, and runtime configuration. Multi-stage builds optimize image size by separating build-time and runtime dependencies.
Kubernetes orchestrates containers across cloud environments. The Kubernetes Ruby client enables programmatic interaction with clusters, supporting automated deployment workflows and dynamic scaling.
Configuration Management
Ansible automates configuration management across cloud environments. Playbooks define infrastructure state and application configuration. The tool manages both cloud provider resources and on-premises infrastructure.
Chef and Puppet provide configuration management with Ruby-based domain-specific languages. These tools maintain desired state across server fleets, handling package installation, file management, and service configuration.
Ruby Deployment Gems
Capistrano automates application deployment to cloud servers. The gem supports multi-stage deployments, rollback capabilities, and custom deployment tasks.
# config/deploy.rb - Capistrano deployment configuration
set :application, 'my_app'
set :repo_url, 'git@github.com:org/my_app.git'
set :deploy_to, '/var/www/my_app'
# Deployment model-specific configuration
deployment_model = ENV.fetch('DEPLOYMENT_MODEL', 'public')
case deployment_model
when 'public'
# Deploy to public cloud instances
role :web, %w[ec2-user@web1.example.com ec2-user@web2.example.com]
role :app, %w[ec2-user@app1.example.com ec2-user@app2.example.com]
role :db, %w[ec2-user@db.example.com]
set :ssh_options, {
keys: %w[~/.ssh/aws_key.pem],
forward_agent: true
}
when 'private'
# Deploy to private cloud instances
role :web, %w[deploy@10.0.1.10 deploy@10.0.1.11]
role :app, %w[deploy@10.0.2.10 deploy@10.0.2.11]
role :db, %w[deploy@10.0.3.10]
when 'hybrid'
# Web tier in public cloud
role :web, %w[ec2-user@web.example.com]
# App and database tier in private cloud
role :app, %w[deploy@10.0.2.10]
role :db, %w[deploy@10.0.3.10]
end
namespace :deploy do
after :updated, :install_dependencies do
on roles(:app) do
within release_path do
execute :bundle, 'install', '--deployment'
end
end
end
end
Kamal deploys containerized Ruby applications with minimal configuration. The tool manages Docker deployments, load balancing, and zero-downtime releases.
Monitoring and Observability
Prometheus collects metrics from Ruby applications through client libraries. The prometheus-client gem exposes application metrics for scraping.
# Application metrics for cloud deployment monitoring
require 'prometheus/client'
class ApplicationMetrics
def initialize
@registry = Prometheus::Client.registry
@request_duration = @registry.histogram(
:http_request_duration_seconds,
docstring: 'Request duration in seconds',
labels: [:method, :path, :status, :cloud_environment]
)
@database_connections = @registry.gauge(
:database_connections_active,
docstring: 'Active database connections',
labels: [:pool, :cloud_environment]
)
@cloud_api_calls = @registry.counter(
:cloud_api_calls_total,
docstring: 'Total cloud provider API calls',
labels: [:provider, :service, :operation]
)
end
def record_request(method:, path:, status:, duration:)
@request_duration.observe(
duration,
labels: {
method: method,
path: path,
status: status,
cloud_environment: deployment_model
}
)
end
def record_cloud_api_call(provider:, service:, operation:)
@cloud_api_calls.increment(
labels: {
provider: provider,
service: service,
operation: operation
}
)
end
private
def deployment_model
ENV.fetch('DEPLOYMENT_MODEL', 'unknown')
end
end
New Relic and Datadog provide commercial application performance monitoring with Ruby agent support. These tools track request performance, database queries, and external service calls across cloud environments.
Service Mesh
Istio and Linkerd provide service mesh capabilities for microservices architectures. Service meshes handle service discovery, load balancing, encryption, and observability across cloud environments. Ruby applications integrate through sidecar proxies without application code changes.
Real-World Applications
Cloud deployment models apply to production systems with varying requirements for scale, reliability, and regulatory compliance. Understanding real-world implementation patterns guides architectural decisions.
E-Commerce Platform - Hybrid Cloud
An e-commerce platform handles customer transactions, inventory management, and order fulfillment. The platform uses hybrid cloud to balance security requirements with scalability demands.
Customer payment processing runs in private cloud for PCI DSS compliance. Payment card data remains within controlled infrastructure meeting strict security requirements. The private environment implements network segmentation, encryption at rest, and comprehensive audit logging.
# Payment processing service in private cloud
class PaymentProcessor
def initialize
# Private cloud payment gateway connection
@gateway = connect_to_private_gateway
@encryptor = PaymentDataEncryptor.new(
key_management_service: :private_cloud_kms
)
end
def process_payment(order:, payment_details:)
# Encrypt sensitive payment data
encrypted_card = @encryptor.encrypt(payment_details[:card_number])
encrypted_cvv = @encryptor.encrypt(payment_details[:cvv])
# Process in private cloud environment
transaction = @gateway.charge(
amount: order.total,
card: encrypted_card,
cvv: encrypted_cvv,
order_id: order.id
)
# Return tokenized reference for storage
{
transaction_id: transaction.id,
payment_token: transaction.token,
status: transaction.status
}
end
private
def connect_to_private_gateway
# Connect to payment gateway in private cloud
PaymentGateway::Client.new(
endpoint: ENV['PRIVATE_PAYMENT_GATEWAY_URL'],
credentials: load_private_credentials,
ssl_verify: true,
ssl_cert: load_client_certificate
)
end
end
Product catalog, search, and content delivery operate in public cloud. These components handle variable traffic patterns and benefit from elastic scaling. CDN integration accelerates content delivery globally. Serverless functions process image transformations and search indexing.
The architecture synchronizes inventory data between environments. Order placement triggers inventory updates in private cloud. Product availability flows to public cloud for catalog display. Message queues coordinate asynchronous updates while maintaining consistency.
Financial Services Platform - Private Cloud
A financial services platform manages investment accounts and executes trades. Regulatory requirements mandate complete control over infrastructure and data.
The platform deploys entirely on private cloud infrastructure, meeting requirements for data residency, audit trails, and security controls. Dedicated hardware ensures isolation from other tenants. Custom network architecture implements defense-in-depth with multiple security layers.
# Trade execution system in private cloud
class TradeExecutionEngine
def initialize
@compliance_checker = ComplianceEngine.new
@risk_manager = RiskManagementSystem.new
@execution_venue = connect_to_trading_venue
@audit_logger = AuditLogger.new(
storage: :private_cloud_compliant_storage
)
end
def execute_trade(account:, instrument:, quantity:, order_type:)
# Log all trade attempts for regulatory compliance
@audit_logger.log_trade_request(
account: account,
instrument: instrument,
quantity: quantity,
timestamp: Time.now.utc,
source_ip: request_ip
)
# Check regulatory compliance
compliance_result = @compliance_checker.validate_trade(
account: account,
instrument: instrument,
quantity: quantity
)
return rejection_response(compliance_result) unless compliance_result.approved?
# Assess risk limits
risk_result = @risk_manager.check_limits(
account: account,
instrument: instrument,
quantity: quantity
)
return rejection_response(risk_result) unless risk_result.within_limits?
# Execute trade
execution = @execution_venue.submit_order(
account_id: account.id,
symbol: instrument.symbol,
quantity: quantity,
order_type: order_type
)
# Log execution results
@audit_logger.log_execution(
execution_id: execution.id,
status: execution.status,
fill_price: execution.price,
timestamp: execution.timestamp
)
execution
end
end
High-frequency trading components require ultra-low latency. Proximity hosting places servers physically close to exchange matching engines. Network optimization includes kernel tuning, direct market access circuits, and hardware acceleration.
Disaster recovery maintains identical infrastructure in geographically separated data centers. Synchronous replication ensures zero data loss. Automated failover activates backup systems within seconds of primary site failure.
Global SaaS Application - Multi-Cloud
A software-as-a-service application serves customers across six continents. Multi-cloud deployment provides regional presence and redundancy against provider failures.
The application deploys on AWS in North America, GCP in Europe, and Alibaba Cloud in Asia. Regional deployments reduce latency for local users. Data residency compliance meets GDPR and local regulations.
# Multi-region request routing
class GlobalRequestRouter
def initialize
@region_mappings = load_region_mappings
@health_checker = RegionHealthChecker.new
end
def route_request(user_location:)
# Determine optimal region based on location
preferred_region = select_region_for_location(user_location)
# Check region health
if @health_checker.region_healthy?(preferred_region)
endpoint_for_region(preferred_region)
else
# Failover to next closest healthy region
fallback_region = select_fallback_region(
user_location: user_location,
failed_region: preferred_region
)
endpoint_for_region(fallback_region)
end
end
private
def select_region_for_location(location)
latitude = location[:latitude]
longitude = location[:longitude]
# Find closest region by geographic distance
@region_mappings.min_by do |region|
distance(latitude, longitude, region[:latitude], region[:longitude])
end[:name]
end
def select_fallback_region(user_location:, failed_region:)
healthy_regions = @region_mappings.reject do |r|
r[:name] == failed_region || !@health_checker.region_healthy?(r[:name])
end
healthy_regions.min_by do |region|
distance(
user_location[:latitude],
user_location[:longitude],
region[:latitude],
region[:longitude]
)
end[:name]
end
def endpoint_for_region(region)
{
api_endpoint: "https://api-#{region}.example.com",
websocket_endpoint: "wss://ws-#{region}.example.com",
cdn_endpoint: "https://cdn-#{region}.example.com"
}
end
def distance(lat1, lon1, lat2, lon2)
# Haversine formula for great-circle distance
rad_per_deg = Math::PI / 180
rm = 6371 # Earth radius in kilometers
dlat_rad = (lat2 - lat1) * rad_per_deg
dlon_rad = (lon2 - lon1) * rad_per_deg
lat1_rad = lat1 * rad_per_deg
lat2_rad = lat2 * rad_per_deg
a = Math.sin(dlat_rad / 2)**2 +
Math.cos(lat1_rad) * Math.cos(lat2_rad) *
Math.sin(dlon_rad / 2)**2
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
rm * c
end
end
Cross-region data synchronization maintains eventual consistency. Write operations occur in the user's region, then replicate asynchronously to other regions. Conflict resolution handles simultaneous updates using last-write-wins or custom merge logic.
Service mesh coordinates traffic across providers. Control plane manages service discovery, authentication, and policy enforcement. Observability tooling aggregates metrics and traces from all regions.
Healthcare Platform - Hybrid Cloud with Air Gap
A healthcare platform manages electronic health records and medical imaging. HIPAA compliance requires strict data controls and audit capabilities.
Protected health information remains in private cloud behind network air gap. No direct internet connectivity prevents unauthorized access. Dedicated circuits connect healthcare facilities to private cloud infrastructure. Multi-factor authentication and role-based access control protect data access.
Public cloud hosts patient portal and appointment scheduling. These components handle PHI references but not actual medical records. API gateway in private cloud mediates requests, enforcing authentication and authorization before returning data.
Data exchange follows HL7 FHIR standards. Integration engine transforms between internal data models and standardized formats. Audit logging captures all data access with immutable records stored for seven years.
Reference
Deployment Model Comparison
| Model | Infrastructure Ownership | Resource Sharing | Control Level | Primary Use Case |
|---|---|---|---|---|
| Public Cloud | Provider-owned | Shared across tenants | Limited | Variable workloads, rapid scaling |
| Private Cloud | Organization-owned or dedicated | Single tenant | Complete | Regulated data, specific requirements |
| Hybrid Cloud | Mixed ownership | Selective sharing | Variable by component | Compliance with flexibility |
| Community Cloud | Shared among organizations | Shared within community | Moderate | Industry-specific requirements |
| Multi-Cloud | Multiple providers | Varies by provider | Complex | Geographic distribution, redundancy |
Cost Model Characteristics
| Aspect | Public Cloud | Private Cloud | Hybrid Cloud |
|---|---|---|---|
| Capital Expenditure | None | High | Moderate |
| Operational Expenditure | Variable, pay-per-use | Fixed with capacity | Mixed |
| Scaling Economics | Linear with usage | Step function at capacity | Optimized for baseline |
| Break-Even Point | Immediate | High sustained utilization | Medium utilization |
Security and Compliance Features
| Requirement | Public Cloud | Private Cloud | Hybrid Cloud |
|---|---|---|---|
| Data Residency Control | Region selection | Complete | Selective by workload |
| Infrastructure Isolation | Logical | Physical | Mixed |
| Compliance Certification | Provider-dependent | Organization-controlled | Workload-dependent |
| Audit Trail Granularity | Service-level | System-level | Variable |
| Custom Security Controls | Limited | Unlimited | Workload-dependent |
Performance Characteristics
| Factor | Public Cloud | Private Cloud | Hybrid Cloud |
|---|---|---|---|
| Latency to Users | Variable by region | Fixed to location | Variable by component |
| Network Throughput | Shared bandwidth | Dedicated bandwidth | Mixed |
| Performance Predictability | Variable | Consistent | Workload-dependent |
| Resource Contention | Possible | Minimal | Selective |
Ruby Gem Ecosystem
| Gem | Purpose | Supported Models |
|---|---|---|
| aws-sdk-s3 | AWS S3 storage | Public, Hybrid |
| aws-sdk-ec2 | AWS compute management | Public, Hybrid |
| google-cloud-storage | GCP storage | Public, Multi-cloud |
| azure-storage-blob | Azure blob storage | Public, Multi-cloud |
| fog | Multi-cloud abstraction | All models |
| diplomat | Consul service discovery | Hybrid, Multi-cloud |
| terraform-ruby | Terraform integration | All models |
Infrastructure as Code Tools
| Tool | Language | Multi-Cloud | State Management |
|---|---|---|---|
| Terraform | HCL | Yes | Remote state |
| CloudFormation | JSON/YAML | AWS only | AWS-managed |
| Pulumi | Ruby/Python/Go/etc | Yes | Pulumi service or S3 |
| Ansible | YAML | Yes | Stateless |
Service Discovery Options
| Solution | Deployment Model | Features |
|---|---|---|
| Consul | All | Service mesh, KV store, health checks |
| etcd | All | Distributed KV store, watch support |
| AWS Cloud Map | Public, Hybrid | AWS service discovery |
| Kubernetes DNS | All | Container service discovery |
Container Orchestration Platforms
| Platform | Complexity | Multi-Cloud Support | Ruby Client |
|---|---|---|---|
| Kubernetes | High | Yes | kubernetes-ruby |
| Amazon ECS | Medium | AWS only | aws-sdk-ecs |
| Google GKE | Medium | GCP only | google-cloud-container |
| Docker Swarm | Low | Yes | Limited |
Monitoring and Observability
| Tool | Type | Deployment Model | Ruby Integration |
|---|---|---|---|
| Prometheus | Metrics | All | prometheus-client |
| Grafana | Visualization | All | grafana-reporter |
| Datadog | APM | All | ddtrace |
| New Relic | APM | All | newrelic_rpm |
| CloudWatch | Metrics/Logs | AWS | aws-sdk-cloudwatch |
Network Connectivity Options
| Technology | Use Case | Bandwidth | Latency |
|---|---|---|---|
| VPN | Hybrid cloud connectivity | Low to medium | Variable |
| Direct Connect | Dedicated hybrid link | High | Low, consistent |
| ExpressRoute | Azure dedicated link | High | Low, consistent |
| Cloud Interconnect | GCP dedicated link | High | Low, consistent |
| SD-WAN | Multi-site connectivity | Medium | Optimized routing |