CrackedRuby CrackedRuby

Overview

Cloud networking represents the abstraction and virtualization of traditional network infrastructure into software-defined components managed through APIs and configuration tools. Unlike physical networking that requires hardware routers, switches, and firewalls, cloud networking creates virtual network topologies that exist as software constructs within cloud provider infrastructure.

The core premise centers on treating network configuration as code. Developers and operations teams define network architectures through API calls, infrastructure-as-code templates, or web console configurations rather than physical cable connections and hardware configurations. This shift enables rapid provisioning, programmatic modification, and version-controlled network infrastructure.

Cloud providers expose networking primitives that mirror physical networking concepts but operate as isolated virtual resources. A virtual private cloud (VPC) creates an isolated network boundary within a cloud region. Subnets divide this space into smaller network segments. Route tables control traffic flow between subnets and external networks. Security groups and network access control lists (ACLs) function as virtual firewalls. Load balancers distribute traffic across multiple compute instances.

The distinction between cloud networking and traditional networking extends beyond virtualization. Cloud networking introduces multi-tenancy where multiple isolated networks share the same physical infrastructure. Software-defined networking (SDN) separates the control plane (routing decisions) from the data plane (packet forwarding). API-driven configuration enables automation at scales impossible with manual hardware configuration.

# Cloud networking as code - defining a VPC structure
require 'aws-sdk-ec2'

ec2 = Aws::EC2::Client.new(region: 'us-east-1')

# Create isolated network space
vpc = ec2.create_vpc({
  cidr_block: '10.0.0.0/16',
  tag_specifications: [{
    resource_type: 'vpc',
    tags: [{ key: 'Name', value: 'production-vpc' }]
  }]
})
# => Creates virtual private cloud with specified IP range

Cloud networking enables geographic distribution across regions and availability zones. Traffic routing adapts to health checks and failover scenarios automatically. Network configurations scale elastically based on demand without physical infrastructure changes.

Key Principles

Virtual Private Cloud (VPC) Isolation

VPCs establish network boundaries that isolate resources from other cloud tenants and the public internet. Each VPC receives a private IP address range defined in CIDR notation. Resources within a VPC can communicate using private IP addresses. Traffic between VPCs requires explicit peering connections or transit gateway configurations.

VPC peering creates direct network routes between two VPCs, enabling resources to communicate as if on the same network. Transitive peering does not exist - if VPC A peers with VPC B, and VPC B peers with VPC C, VPC A cannot directly reach VPC C without an explicit peering connection.

Subnets and Availability Zones

Subnets subdivide VPC IP ranges into smaller network segments, each associated with a specific availability zone. Public subnets contain resources accessible from the internet through an internet gateway. Private subnets contain resources accessible only within the VPC or through VPN/Direct Connect links.

The subnet's route table determines traffic flow. A subnet becomes public when its route table includes a route to an internet gateway for destination 0.0.0.0/0. Private subnets route internet-bound traffic through a NAT gateway located in a public subnet, enabling outbound internet access while blocking inbound connections.

Security Groups and Network ACLs

Security groups operate as stateful virtual firewalls at the instance level. When a security group allows an inbound connection, the response traffic automatically receives permission regardless of outbound rules. Each instance can associate with multiple security groups, with rules evaluated collectively.

Network ACLs function as stateless firewalls at the subnet level. Both inbound and outbound traffic require explicit rules. ACL rules process in numerical order, with the first match determining the action. The default network ACL allows all traffic; custom ACLs deny all traffic until rules explicitly permit it.

Routing and Gateways

Route tables contain rules that determine network traffic paths. Each subnet associates with exactly one route table. Routes specify destination CIDR blocks and targets (internet gateway, NAT gateway, VPC peering connection, virtual private gateway).

Internet gateways enable communication between VPC resources and the internet. NAT gateways allow private subnet instances to initiate outbound internet connections while remaining unreachable from the internet. Virtual private gateways terminate VPN connections. Transit gateways act as network hubs, connecting multiple VPCs and on-premises networks.

Load Balancing and Traffic Distribution

Load balancers distribute incoming traffic across multiple targets (instances, containers, IP addresses) within one or more availability zones. Application load balancers operate at layer 7, routing based on HTTP headers, paths, or host names. Network load balancers operate at layer 4, routing based on IP protocol data with ultra-low latency.

Health checks monitor target availability. Load balancers automatically route traffic only to healthy targets. Connection draining ensures in-flight requests complete before removing targets from service.

DNS and Service Discovery

Cloud networking integrates DNS resolution for internal and external name resolution. Private hosted zones provide DNS services for resources within a VPC without exposing names to the public internet. Split-view DNS serves different responses for internal versus external queries.

Service discovery mechanisms enable dynamic service registration and discovery. Services register their network locations, and clients query the service registry rather than using hardcoded IP addresses.

Implementation Approaches

Hub-and-Spoke Architecture

Hub-and-spoke topology centralizes shared services in a hub VPC with multiple spoke VPCs connecting through VPC peering or transit gateways. The hub contains centralized security services, monitoring systems, or shared databases. Spokes contain application-specific resources isolated from each other.

This architecture simplifies network management by reducing the number of connections. Instead of N×(N-1)/2 peering connections for full mesh topology, hub-and-spoke requires only N connections. Transit gateways support this pattern at scale, enabling routing between spokes through the hub.

Traffic inspection and logging centralize in the hub. Security appliances, intrusion detection systems, and network packet analyzers deploy once rather than in each spoke. The hub becomes a single point of policy enforcement.

Multi-VPC Strategy

Organizations divide infrastructure across multiple VPCs based on environments (development, staging, production), compliance requirements, or organizational boundaries. Each VPC maintains complete isolation unless explicitly connected.

Environment separation prevents accidental changes in production from development experiments. Compliance requirements often mandate physical or logical separation of regulated data. Organizational VPCs enable different teams to manage their own network infrastructure independently.

Cross-VPC communication requires deliberate configuration. VPC peering connections establish direct network routes. PrivateLink exposes services across VPC boundaries without peering. Transit gateways enable complex routing topologies.

Hybrid Cloud Connectivity

Hybrid architectures connect cloud VPCs with on-premises data centers. VPN connections encrypt traffic over the public internet. Direct Connect establishes dedicated network circuits between on-premises facilities and cloud regions.

VPN connections support up to 1.25 Gbps per tunnel. Multiple tunnels can aggregate bandwidth. Direct Connect provides dedicated bandwidth from 1 Gbps to 100 Gbps with consistent network performance.

Route propagation determines traffic paths between cloud and on-premises networks. Border Gateway Protocol (BGP) enables dynamic routing updates. Static routes provide explicit control but require manual updates when network topology changes.

Service Mesh Integration

Service meshes layer additional networking capabilities on top of cloud networking infrastructure. Sidecar proxies intercept all network traffic to and from application containers. The service mesh control plane configures these proxies to implement traffic routing, load balancing, retry logic, circuit breaking, and mutual TLS encryption.

Cloud networking provides the underlying connectivity between instances. The service mesh adds application-level networking features. Cloud load balancers distribute traffic to mesh-enabled applications. The mesh handles request-level routing and resilience.

Ruby Implementation

AWS SDK VPC Management

require 'aws-sdk-ec2'

class NetworkProvisioner
  def initialize(region)
    @ec2 = Aws::EC2::Client.new(region: region)
    @resource = Aws::EC2::Resource.new(client: @ec2)
  end

  def create_network_stack(cidr_block, subnet_configs)
    # Create VPC
    vpc = @resource.create_vpc({
      cidr_block: cidr_block,
      amazon_provided_ipv6_cidr_block: false
    })
    
    vpc.create_tags({ tags: [{ key: 'Name', value: 'app-vpc' }] })
    vpc.modify_attribute({ enable_dns_hostnames: { value: true } })
    
    # Create Internet Gateway
    igw = @resource.create_internet_gateway
    vpc.attach_internet_gateway({ internet_gateway_id: igw.id })
    
    # Create subnets across availability zones
    subnets = subnet_configs.map do |config|
      subnet = vpc.create_subnet({
        cidr_block: config[:cidr],
        availability_zone: config[:az]
      })
      
      subnet.create_tags({
        tags: [
          { key: 'Name', value: config[:name] },
          { key: 'Type', value: config[:type] }
        ]
      })
      
      subnet
    end
    
    # Configure route tables
    public_subnets = subnets.select { |s| s.tags.any? { |t| t.value == 'public' } }
    setup_public_routing(vpc, igw, public_subnets)
    
    { vpc: vpc, subnets: subnets, internet_gateway: igw }
  end

  private

  def setup_public_routing(vpc, igw, subnets)
    route_table = vpc.create_route_table
    route_table.create_route({
      destination_cidr_block: '0.0.0.0/0',
      gateway_id: igw.id
    })
    
    subnets.each do |subnet|
      route_table.associate_with_subnet({ subnet_id: subnet.id })
    end
  end
end

# Usage
provisioner = NetworkProvisioner.new('us-east-1')
network = provisioner.create_network_stack('10.0.0.0/16', [
  { cidr: '10.0.1.0/24', az: 'us-east-1a', name: 'public-1a', type: 'public' },
  { cidr: '10.0.2.0/24', az: 'us-east-1b', name: 'public-1b', type: 'public' },
  { cidr: '10.0.11.0/24', az: 'us-east-1a', name: 'private-1a', type: 'private' }
])
# => { vpc: #<Aws::EC2::Vpc>, subnets: [...], internet_gateway: #<Aws::EC2::InternetGateway> }

Security Group Configuration

require 'aws-sdk-ec2'

class SecurityGroupManager
  def initialize(ec2_client)
    @ec2 = ec2_client
  end

  def create_web_tier_security(vpc_id)
    # Application load balancer security group
    alb_sg = @ec2.create_security_group({
      group_name: 'alb-security-group',
      description: 'Security group for application load balancer',
      vpc_id: vpc_id
    })
    
    # Allow HTTP/HTTPS from internet
    @ec2.authorize_security_group_ingress({
      group_id: alb_sg.group_id,
      ip_permissions: [
        {
          ip_protocol: 'tcp',
          from_port: 80,
          to_port: 80,
          ip_ranges: [{ cidr_ip: '0.0.0.0/0', description: 'HTTP from internet' }]
        },
        {
          ip_protocol: 'tcp',
          from_port: 443,
          to_port: 443,
          ip_ranges: [{ cidr_ip: '0.0.0.0/0', description: 'HTTPS from internet' }]
        }
      ]
    })
    
    # Web server security group
    web_sg = @ec2.create_security_group({
      group_name: 'web-security-group',
      description: 'Security group for web servers',
      vpc_id: vpc_id
    })
    
    # Allow traffic only from ALB
    @ec2.authorize_security_group_ingress({
      group_id: web_sg.group_id,
      ip_permissions: [{
        ip_protocol: 'tcp',
        from_port: 8080,
        to_port: 8080,
        user_id_group_pairs: [{
          group_id: alb_sg.group_id,
          description: 'Application traffic from ALB'
        }]
      }]
    })
    
    # Database security group
    db_sg = @ec2.create_security_group({
      group_name: 'database-security-group',
      description: 'Security group for databases',
      vpc_id: vpc_id
    })
    
    # Allow database connections only from web tier
    @ec2.authorize_security_group_ingress({
      group_id: db_sg.group_id,
      ip_permissions: [{
        ip_protocol: 'tcp',
        from_port: 5432,
        to_port: 5432,
        user_id_group_pairs: [{
          group_id: web_sg.group_id,
          description: 'PostgreSQL from web tier'
        }]
      }]
    })
    
    { alb: alb_sg, web: web_sg, database: db_sg }
  end
end

# Usage
manager = SecurityGroupManager.new(Aws::EC2::Client.new)
security_groups = manager.create_web_tier_security('vpc-12345678')
# => Creates layered security group architecture

Google Cloud Platform Networking

require 'google/cloud/compute'

class GCPNetworkManager
  def initialize(project_id)
    @compute = Google::Cloud::Compute.new(project: project_id)
  end

  def create_vpc_network(network_name, subnet_configs)
    # Create custom VPC network
    network = @compute.create_network(
      name: network_name,
      auto_create_subnetworks: false,
      routing_config: {
        routing_mode: 'REGIONAL'
      }
    )
    
    # Create subnets in different regions
    subnets = subnet_configs.map do |config|
      @compute.create_subnetwork(
        name: config[:name],
        network: network.self_link,
        ip_cidr_range: config[:cidr],
        region: config[:region],
        private_ip_google_access: true
      )
    end
    
    { network: network, subnets: subnets }
  end

  def configure_firewall_rules(network_name)
    rules = []
    
    # Allow internal traffic
    rules << @compute.create_firewall(
      name: "#{network_name}-allow-internal",
      network: "projects/#{@compute.project}/global/networks/#{network_name}",
      source_ranges: ['10.0.0.0/8'],
      allowed: [
        { ip_protocol: 'tcp', ports: ['0-65535'] },
        { ip_protocol: 'udp', ports: ['0-65535'] },
        { ip_protocol: 'icmp' }
      ]
    )
    
    # Allow SSH from specific IP ranges
    rules << @compute.create_firewall(
      name: "#{network_name}-allow-ssh",
      network: "projects/#{@compute.project}/global/networks/#{network_name}",
      source_ranges: ['35.235.240.0/20'],
      allowed: [{ ip_protocol: 'tcp', ports: ['22'] }]
    )
    
    # Allow health checks
    rules << @compute.create_firewall(
      name: "#{network_name}-allow-health-checks",
      network: "projects/#{@compute.project}/global/networks/#{network_name}",
      source_ranges: ['35.191.0.0/16', '130.211.0.0/22'],
      allowed: [{ ip_protocol: 'tcp' }]
    )
    
    rules
  end
end

# Usage
manager = GCPNetworkManager.new('my-project-id')
network = manager.create_vpc_network('production-network', [
  { name: 'subnet-us-east', cidr: '10.1.0.0/24', region: 'us-east1' },
  { name: 'subnet-us-west', cidr: '10.2.0.0/24', region: 'us-west1' }
])
# => Creates multi-region VPC network with subnets

Load Balancer Configuration with Ruby

require 'aws-sdk-elasticloadbalancingv2'

class LoadBalancerConfigurator
  def initialize(region)
    @elb = Aws::ElasticLoadBalancingV2::Client.new(region: region)
  end

  def create_application_load_balancer(name, subnet_ids, security_group_ids, vpc_id)
    # Create application load balancer
    lb_response = @elb.create_load_balancer({
      name: name,
      subnets: subnet_ids,
      security_groups: security_group_ids,
      scheme: 'internet-facing',
      type: 'application',
      ip_address_type: 'ipv4'
    })
    
    lb_arn = lb_response.load_balancers[0].load_balancer_arn
    
    # Create target group
    tg_response = @elb.create_target_group({
      name: "#{name}-targets",
      protocol: 'HTTP',
      port: 8080,
      vpc_id: vpc_id,
      health_check_protocol: 'HTTP',
      health_check_path: '/health',
      health_check_interval_seconds: 30,
      health_check_timeout_seconds: 5,
      healthy_threshold_count: 2,
      unhealthy_threshold_count: 3,
      matcher: { http_code: '200' }
    })
    
    tg_arn = tg_response.target_groups[0].target_group_arn
    
    # Create listener with routing rules
    listener_response = @elb.create_listener({
      load_balancer_arn: lb_arn,
      protocol: 'HTTP',
      port: 80,
      default_actions: [{
        type: 'forward',
        target_group_arn: tg_arn
      }]
    })
    
    # Add path-based routing rule
    @elb.create_rule({
      listener_arn: listener_response.listeners[0].listener_arn,
      conditions: [{
        field: 'path-pattern',
        values: ['/api/*']
      }],
      priority: 1,
      actions: [{
        type: 'forward',
        target_group_arn: tg_arn
      }]
    })
    
    {
      load_balancer_arn: lb_arn,
      target_group_arn: tg_arn,
      dns_name: lb_response.load_balancers[0].dns_name
    }
  end

  def register_targets(target_group_arn, instance_ids)
    targets = instance_ids.map { |id| { id: id, port: 8080 } }
    
    @elb.register_targets({
      target_group_arn: target_group_arn,
      targets: targets
    })
  end
end

# Usage
configurator = LoadBalancerConfigurator.new('us-east-1')
lb = configurator.create_application_load_balancer(
  'production-alb',
  ['subnet-123', 'subnet-456'],
  ['sg-789'],
  'vpc-12345'
)
configurator.register_targets(lb[:target_group_arn], ['i-abc123', 'i-def456'])
# => Creates ALB with health checks and registers instances

Security Implications

Network Segmentation and Isolation

Defense in depth requires multiple network boundaries. Public subnets contain only resources that require direct internet access (load balancers, bastion hosts, NAT gateways). Application servers reside in private subnets without direct internet routes. Database and cache layers occupy separate private subnets with restricted security group rules.

Each tier restricts communication to necessary ports and protocols. Web servers accept connections only from load balancers. Application servers accept connections only from web servers. Database servers accept connections only from application servers. This layered approach limits blast radius when a single component becomes compromised.

Network ACLs provide subnet-level protection as a secondary defense layer. While security groups allow fine-grained instance-level control, network ACLs enforce baseline rules at the subnet boundary. Stateless ACL rules require explicit allow rules for both request and response traffic.

VPC Flow Logs and Traffic Analysis

VPC flow logs capture metadata about network traffic flowing through VPC network interfaces. Each flow log record contains source and destination IP addresses, ports, protocol, packet count, byte count, and accept/reject action. Flow logs do not capture packet contents.

Analyzing flow logs reveals traffic patterns, identifies unauthorized access attempts, and troubleshoots connectivity issues. Aggregating flow logs in a centralized log analytics system enables correlation across multiple VPCs and accounts.

require 'aws-sdk-ec2'
require 'aws-sdk-cloudwatchlogs'

class FlowLogAnalyzer
  def initialize(region)
    @ec2 = Aws::EC2::Client.new(region: region)
    @logs = Aws::CloudWatchLogs::Client.new(region: region)
  end

  def enable_vpc_flow_logs(vpc_id, log_group_name)
    # Create CloudWatch log group
    @logs.create_log_group({ log_group_name: log_group_name })
    
    # Create IAM role for flow logs (role creation not shown)
    role_arn = 'arn:aws:iam::123456789012:role/flowlogsRole'
    
    # Enable flow logs
    @ec2.create_flow_logs({
      resource_type: 'VPC',
      resource_ids: [vpc_id],
      traffic_type: 'ALL',
      log_destination_type: 'cloud-watch-logs',
      log_group_name: log_group_name,
      deliver_logs_permission_arn: role_arn
    })
  end

  def analyze_rejected_traffic(log_group_name, hours = 24)
    start_time = (Time.now - hours * 3600).to_i * 1000
    end_time = Time.now.to_i * 1000
    
    # Query rejected connection attempts
    query = <<~QUERY
      fields @timestamp, srcAddr, dstAddr, dstPort, protocol, action
      | filter action = 'REJECT'
      | stats count() as rejectedCount by srcAddr, dstPort
      | sort rejectedCount desc
      | limit 20
    QUERY
    
    query_response = @logs.start_query({
      log_group_name: log_group_name,
      start_time: start_time,
      end_time: end_time,
      query_string: query
    })
    
    # Poll for results
    query_id = query_response.query_id
    sleep(2)
    
    results = @logs.get_query_results({ query_id: query_id })
    results.results.map do |result|
      result.map { |field| [field.field, field.value] }.to_h
    end
  end
end

# Usage
analyzer = FlowLogAnalyzer.new('us-east-1')
analyzer.enable_vpc_flow_logs('vpc-12345', '/aws/vpc/flowlogs')
suspicious_ips = analyzer.analyze_rejected_traffic('/aws/vpc/flowlogs', 24)
# => Returns source IPs with most rejected connection attempts

Private Link and Service Endpoints

PrivateLink enables private connectivity to cloud services and third-party SaaS applications without traversing the public internet. Traffic remains within the cloud provider network. Service endpoints create private connections from VPC to supported services.

Without PrivateLink, accessing cloud storage or managed databases routes through internet gateways or NAT gateways, exposing traffic to potential interception. PrivateLink establishes a network interface in the VPC with a private IP address. Applications connect to this interface, and the cloud provider routes traffic internally.

Third-party services expose endpoints through PrivateLink. Instead of allowing internet access to SaaS APIs, VPCs connect to vendor-provided endpoints. This eliminates public internet exposure for sensitive API traffic.

Network Access Control and Least Privilege

Zero trust networking assumes no implicit trust based on network location. Every connection requires authentication and authorization, even from within the VPC. Security groups default to deny-all and require explicit allow rules.

Source security groups in rules enable dynamic authorization. Instead of allowing traffic from specific IP ranges that change as infrastructure scales, rules reference other security groups. When instances join or leave an autoscaling group, security group membership updates automatically.

Regularly auditing security group rules identifies overly permissive configurations. Rules allowing 0.0.0.0/0 source access on non-standard ports require justification. Unused security groups accumulate over time and require cleanup to maintain clear security posture.

DDoS Protection and Rate Limiting

Cloud load balancers absorb volumetric DDoS attacks by distributing traffic across multiple availability zones. Connection state tracking and rate limiting protect backend services from overwhelming traffic.

Web Application Firewalls (WAF) integrate with load balancers to filter malicious requests before they reach applications. WAF rules detect common attack patterns including SQL injection, cross-site scripting, and bot traffic. Custom rules based on request headers, geographic location, or rate limits block specific threats.

Network-level DDoS protection services analyze traffic patterns and automatically mitigate large-scale attacks. Traffic scrubbing redirects attack traffic to analysis systems while allowing legitimate traffic through. These systems handle attacks at scales exceeding individual organization capacity.

Tools & Ecosystem

Infrastructure as Code with Terraform

Terraform defines cloud networking infrastructure through declarative configuration files. The same Terraform configuration deploys identical network architectures across multiple cloud providers or regions.

# Ruby script to generate Terraform configuration
class TerraformNetworkGenerator
  def generate_vpc_config(vpc_name, cidr_block, subnet_configs)
    config = {
      resource: {
        aws_vpc: {
          vpc_name => {
            cidr_block: cidr_block,
            enable_dns_hostnames: true,
            enable_dns_support: true,
            tags: { Name: vpc_name }
          }
        },
        aws_subnet: {},
        aws_internet_gateway: {
          "#{vpc_name}_igw" => {
            vpc_id: "${aws_vpc.#{vpc_name}.id}",
            tags: { Name: "#{vpc_name}-igw" }
          }
        }
      }
    }
    
    subnet_configs.each do |subnet|
      config[:resource][:aws_subnet][subnet[:name]] = {
        vpc_id: "${aws_vpc.#{vpc_name}.id}",
        cidr_block: subnet[:cidr],
        availability_zone: subnet[:az],
        map_public_ip_on_launch: subnet[:public],
        tags: { Name: subnet[:name] }
      }
    end
    
    require 'json'
    JSON.pretty_generate(config)
  end
end

# Usage
generator = TerraformNetworkGenerator.new
terraform_config = generator.generate_vpc_config('production', '10.0.0.0/16', [
  { name: 'public-1a', cidr: '10.0.1.0/24', az: 'us-east-1a', public: true },
  { name: 'private-1a', cidr: '10.0.11.0/24', az: 'us-east-1a', public: false }
])
File.write('network.tf.json', terraform_config)
# => Generates Terraform configuration file

Network Monitoring and Observability

CloudWatch metrics track network interface statistics, load balancer metrics, and VPN connection status. Custom metrics from application logs provide deeper visibility into request patterns and error rates.

Third-party monitoring tools aggregate metrics across multiple cloud providers. Datadog, New Relic, and Prometheus collect network performance data and correlate with application metrics. Time-series databases store network metrics for trend analysis and capacity planning.

Network performance monitoring detects packet loss, latency increases, and bandwidth saturation. Synthetic monitoring generates test traffic to measure performance from different geographic locations.

Software-Defined Networking Controllers

SDN controllers separate network control logic from packet forwarding. The control plane (centralized controller) makes routing decisions and updates forwarding rules on network devices (data plane).

OpenFlow protocol enables controllers to program flow tables on switches. Controllers maintain global network state and calculate optimal paths. Data plane devices forward packets according to these centralized decisions.

Cloud providers implement proprietary SDN controllers managing virtualized network infrastructure. These controllers handle VPC routing, security group enforcement, and load balancer configuration transparently.

Container Networking Interfaces

Container orchestration platforms (Kubernetes, Amazon ECS) require networking solutions that assign IP addresses to containers, route traffic between containers, and integrate with cloud load balancers.

CNI plugins implement different networking models. Overlay networks create virtual networks spanning multiple hosts. Each container receives an IP address from the overlay network's address space. Encapsulation protocols (VXLAN, GENEVE) tunnel container traffic through the underlying cloud network.

AWS VPC CNI plugin assigns EC2 instance IP addresses directly to containers. Each pod receives an IP address from the VPC subnet. This eliminates overlay network complexity and enables direct security group application to pods.

DNS Management Tools

Route53 (AWS), Cloud DNS (GCP), and Azure DNS provide authoritative DNS hosting with global anycast networks. DNS queries resolve from geographically distributed name servers reducing latency.

Dynamic DNS updates enable service discovery for ephemeral infrastructure. Applications register DNS records when starting and remove records during shutdown. Health checks ensure DNS records point only to healthy instances.

Private DNS zones resolve internal service names without exposing them publicly. Split-horizon DNS serves different responses based on query source. External queries receive public IP addresses while internal queries receive private IP addresses.

Real-World Applications

Multi-Tier Application Architecture

Production applications separate concerns across network tiers. The presentation tier receives user requests through a public load balancer in public subnets. The application tier processes business logic in private subnets without direct internet access. The data tier maintains state in private subnets with restricted security group access.

require 'aws-sdk-ec2'
require 'aws-sdk-elasticloadbalancingv2'
require 'aws-sdk-rds'

class ProductionNetworkDeployer
  def initialize(region)
    @ec2 = Aws::EC2::Client.new(region: region)
    @elb = Aws::ElasticLoadBalancingV2::Client.new(region: region)
    @rds = Aws::RDS::Client.new(region: region)
    @resource = Aws::EC2::Resource.new(client: @ec2)
  end

  def deploy_three_tier_network
    # Create VPC with CIDR block
    vpc = @resource.create_vpc({ cidr_block: '10.0.0.0/16' })
    vpc.wait_until_available
    vpc.modify_attribute({ enable_dns_hostnames: { value: true } })
    
    # Create subnets across 2 availability zones
    public_subnet_1a = create_subnet(vpc, '10.0.1.0/24', 'us-east-1a', 'public')
    public_subnet_1b = create_subnet(vpc, '10.0.2.0/24', 'us-east-1b', 'public')
    app_subnet_1a = create_subnet(vpc, '10.0.11.0/24', 'us-east-1a', 'application')
    app_subnet_1b = create_subnet(vpc, '10.0.12.0/24', 'us-east-1b', 'application')
    db_subnet_1a = create_subnet(vpc, '10.0.21.0/24', 'us-east-1a', 'database')
    db_subnet_1b = create_subnet(vpc, '10.0.22.0/24', 'us-east-1b', 'database')
    
    # Configure internet gateway and NAT gateways
    igw = @resource.create_internet_gateway
    vpc.attach_internet_gateway({ internet_gateway_id: igw.id })
    
    nat_1a = create_nat_gateway(public_subnet_1a)
    nat_1b = create_nat_gateway(public_subnet_1b)
    
    # Configure routing
    setup_public_routing(vpc, igw, [public_subnet_1a, public_subnet_1b])
    setup_private_routing(vpc, app_subnet_1a, nat_1a)
    setup_private_routing(vpc, app_subnet_1b, nat_1b)
    
    # Create security groups
    alb_sg = create_alb_security_group(vpc.id)
    app_sg = create_app_security_group(vpc.id, alb_sg)
    db_sg = create_db_security_group(vpc.id, app_sg)
    
    # Deploy application load balancer
    alb = create_application_load_balancer(
      [public_subnet_1a.id, public_subnet_1b.id],
      [alb_sg]
    )
    
    # Create database subnet group
    db_subnet_group = @rds.create_db_subnet_group({
      db_subnet_group_name: 'production-db-subnet',
      db_subnet_group_description: 'Database subnet group',
      subnet_ids: [db_subnet_1a.id, db_subnet_1b.id]
    })
    
    {
      vpc_id: vpc.id,
      alb_dns: alb[:dns_name],
      app_subnets: [app_subnet_1a.id, app_subnet_1b.id],
      db_subnet_group: db_subnet_group.db_subnet_group.db_subnet_group_name
    }
  end

  private

  def create_subnet(vpc, cidr, az, tier)
    subnet = vpc.create_subnet({
      cidr_block: cidr,
      availability_zone: az
    })
    subnet.create_tags({ tags: [{ key: 'Tier', value: tier }] })
    subnet
  end

  def create_nat_gateway(subnet)
    # Allocate Elastic IP
    eip = @ec2.allocate_address({ domain: 'vpc' })
    
    # Create NAT Gateway
    nat = @ec2.create_nat_gateway({
      subnet_id: subnet.id,
      allocation_id: eip.allocation_id
    })
    
    # Wait for NAT Gateway to become available
    @ec2.wait_until(:nat_gateway_available, { nat_gateway_ids: [nat.nat_gateway.nat_gateway_id] })
    nat.nat_gateway.nat_gateway_id
  end

  def setup_public_routing(vpc, igw, subnets)
    route_table = vpc.create_route_table
    route_table.create_route({
      destination_cidr_block: '0.0.0.0/0',
      gateway_id: igw.id
    })
    subnets.each { |subnet| route_table.associate_with_subnet({ subnet_id: subnet.id }) }
  end

  def setup_private_routing(vpc, subnet, nat_gateway_id)
    route_table = vpc.create_route_table
    route_table.create_route({
      destination_cidr_block: '0.0.0.0/0',
      nat_gateway_id: nat_gateway_id
    })
    route_table.associate_with_subnet({ subnet_id: subnet.id })
  end

  def create_alb_security_group(vpc_id)
    sg = @ec2.create_security_group({
      group_name: 'alb-sg',
      description: 'ALB security group',
      vpc_id: vpc_id
    })
    
    @ec2.authorize_security_group_ingress({
      group_id: sg.group_id,
      ip_permissions: [
        { ip_protocol: 'tcp', from_port: 443, to_port: 443, ip_ranges: [{ cidr_ip: '0.0.0.0/0' }] }
      ]
    })
    sg.group_id
  end

  def create_app_security_group(vpc_id, alb_sg_id)
    sg = @ec2.create_security_group({
      group_name: 'app-sg',
      description: 'Application tier security group',
      vpc_id: vpc_id
    })
    
    @ec2.authorize_security_group_ingress({
      group_id: sg.group_id,
      ip_permissions: [{
        ip_protocol: 'tcp',
        from_port: 8080,
        to_port: 8080,
        user_id_group_pairs: [{ group_id: alb_sg_id }]
      }]
    })
    sg.group_id
  end

  def create_db_security_group(vpc_id, app_sg_id)
    sg = @ec2.create_security_group({
      group_name: 'db-sg',
      description: 'Database tier security group',
      vpc_id: vpc_id
    })
    
    @ec2.authorize_security_group_ingress({
      group_id: sg.group_id,
      ip_permissions: [{
        ip_protocol: 'tcp',
        from_port: 5432,
        to_port: 5432,
        user_id_group_pairs: [{ group_id: app_sg_id }]
      }]
    })
    sg.group_id
  end

  def create_application_load_balancer(subnet_ids, security_group_ids)
    lb = @elb.create_load_balancer({
      name: 'production-alb',
      subnets: subnet_ids,
      security_groups: security_group_ids,
      scheme: 'internet-facing',
      type: 'application'
    })
    { dns_name: lb.load_balancers[0].dns_name }
  end
end

# Usage
deployer = ProductionNetworkDeployer.new('us-east-1')
network = deployer.deploy_three_tier_network
# => Deploys complete three-tier network architecture

Cross-Region Disaster Recovery

Disaster recovery architectures replicate critical infrastructure across geographic regions. Primary region handles production traffic. Secondary region maintains warm standby or active-active configuration.

VPC peering across regions establishes private connectivity for data replication. Database replicas in the secondary region receive continuous updates. Applications deploy identically in both regions with traffic routing based on health checks and failover policies.

DNS-based failover detects primary region health and redirects traffic to secondary region. Route53 health checks monitor endpoint availability. Failed health checks trigger automatic DNS record updates pointing to secondary region load balancers.

Microservices Service Mesh

Service mesh implementations add sidecar proxies to each microservice instance. These proxies intercept all network traffic and implement features including mutual TLS, circuit breaking, retry logic, and distributed tracing.

Cloud networking provides subnet isolation and security group filtering. Service mesh adds application-level network management. Load balancers distribute traffic to service mesh ingress gateways. The mesh handles internal service-to-service communication.

Observability improves dramatically as the mesh exports detailed metrics about every request. Tracing headers propagate through service calls, creating complete request flow visibility. Mesh control planes maintain service registries enabling dynamic service discovery.

Reference

VPC Components

Component Description Use Case
VPC Isolated virtual network within cloud provider infrastructure Network boundary for multi-tier applications
Subnet Subdivision of VPC IP range associated with availability zone Separate public and private resources
Internet Gateway Horizontally scaled, redundant gateway for internet traffic Enable internet access for public subnets
NAT Gateway Managed network address translation service Outbound internet access from private subnets
Route Table Set of routing rules determining network traffic paths Control traffic flow between subnets and gateways
Security Group Stateful virtual firewall at instance level Control inbound and outbound traffic to instances
Network ACL Stateless firewall at subnet level Additional subnet boundary protection
VPC Peering Direct network connection between two VPCs Private connectivity between VPCs
Transit Gateway Network hub connecting multiple VPCs and on-premises networks Simplified multi-VPC connectivity
VPN Gateway IPsec VPN connection termination point Encrypted connectivity to on-premises networks
Direct Connect Dedicated network connection to cloud provider High-bandwidth, consistent latency to cloud

Security Group Rules

Direction Type Protocol Port Range Source/Destination Purpose
Inbound HTTP TCP 80 0.0.0.0/0 Public web traffic
Inbound HTTPS TCP 443 0.0.0.0/0 Public secure web traffic
Inbound SSH TCP 22 Corporate IP range Administrative access
Inbound Custom TCP 8080 Security group ID Application traffic from load balancer
Inbound PostgreSQL TCP 5432 Security group ID Database access from application tier
Outbound All traffic All All 0.0.0.0/0 Default outbound rule

Load Balancer Types

Type OSI Layer Protocol Support Use Case Latency
Application Load Balancer Layer 7 HTTP, HTTPS, gRPC Web applications with advanced routing Low
Network Load Balancer Layer 4 TCP, UDP, TLS High-performance applications requiring static IP Ultra-low
Gateway Load Balancer Layer 3 IP packets Third-party virtual appliances Low
Classic Load Balancer Layer 4/7 HTTP, HTTPS, TCP, SSL Legacy applications Low

Common CIDR Blocks

CIDR Block IP Range Usable IPs Typical Use
10.0.0.0/16 10.0.0.0 - 10.0.255.255 65,536 Large VPC
10.0.0.0/24 10.0.0.0 - 10.0.0.255 256 Single subnet
172.16.0.0/12 172.16.0.0 - 172.31.255.255 1,048,576 Enterprise VPC
192.168.0.0/16 192.168.0.0 - 192.168.255.255 65,536 Development VPC

AWS SDK for Ruby Network Operations

Operation Method Returns
Create VPC Aws::EC2::Resource#create_vpc Aws::EC2::Vpc
Create Subnet Aws::EC2::Vpc#create_subnet Aws::EC2::Subnet
Create Security Group Aws::EC2::Client#create_security_group Security group ID
Authorize Ingress Aws::EC2::Client#authorize_security_group_ingress Boolean
Create Route Table Aws::EC2::Vpc#create_route_table Aws::EC2::RouteTable
Create NAT Gateway Aws::EC2::Client#create_nat_gateway NAT gateway object
Create Load Balancer Aws::ElasticLoadBalancingV2::Client#create_load_balancer Load balancer details
Describe VPCs Aws::EC2::Client#describe_vpcs Array of VPC objects
Enable Flow Logs Aws::EC2::Client#create_flow_logs Flow log IDs

Network Performance Metrics

Metric Description Threshold
Packet Loss Percentage of packets not reaching destination < 0.1% acceptable
Latency Time for packet to travel from source to destination < 50ms regional, < 200ms global
Bandwidth Maximum data transfer rate Depends on link capacity
Jitter Variation in packet arrival times < 30ms for real-time applications
Connection Rate New connections per second Monitored for capacity planning
Active Connections Current established connections Compared against limits