# Sandip Basnet - Full LLM & RAG Knowledge Base Dataset
> Official full-text content export for Sandip Basnet portfolio website (https://sandipbasnet.com.np). Designed for LLM ingestion, AI answer retrieval engines (Perplexity, ChatGPT, Claude, SearchGPT, Gemini), and semantic search indexes.

## Personal & Professional Profile
- **Full Name:** Sandip Basnet
- **Handle:** mondyfy
- **Role:** AWS Certified Solutions Architect & SRE Lead
- **Focus:** Designing Distributed Architectures, PostgreSQL HA & High-Scale Infrastructure
- **Location:** Kathmandu, Nepal 🇳🇵
- **Contact Email:** explorer.sandip@gmail.com
- **WhatsApp / Direct Phone:** +977 982-7706245 (https://wa.me/9779827706245)
- **GitHub:** https://github.com/mondyfy
- **LinkedIn:** https://www.linkedin.com/in/sandipbasnet/
- **Twitter:** https://twitter.com/mondy

## Summary Bio
AWS Certified Solutions Architect and Systems Reliability Lead based in Kathmandu, Nepal. Specializing in high-availability database clusters (Patroni/PostgreSQL), cloud-native microservices, automated ETL pipelines, and resilient distributed architectures.

---

## Section 1: Detailed Software & Infrastructure Projects
### Project: PostgreSQL High Availability Cluster Blueprint
- **Category:** devops
- **Repository:** https://github.com/mondyfy
- **Tags:** PostgreSQL, Patroni, Etcd, Ansible, Docker, Prometheus, Grafana
- **Description:** Enterprise automation blueprint for PostgreSQL HA clustering, Patroni consensus failover, pgBackRest S3 backups, and Grafana telemetry.
- **In-Depth Details:** Designed for mission-critical relational database reliability. Features automated leader failover via Patroni and Etcd, zero-data-loss WAL archiving to cloud object storage, connection pooling with PgBouncer, and real-time deadlock monitoring.
- **Architecture Highlights:**
  - Patroni + Etcd consensus cluster for automatic master failover without data divergence
  - pgBackRest differential & full backup to AWS S3 object storage with point-in-time recovery
  - Custom Grafana dashboard alerting on replication lag, locks, and connection pool saturation

---

### Project: info-nepal (NPM Metadata Distribution)
- **Category:** opensource
- **Repository:** https://github.com/mondyfy/nepal-info
- **NPM Registry:** https://www.npmjs.com/package/info-nepal
- **Tags:** Node.js, TypeScript, NPM, Open Source, Nepal GIS
- **Description:** High-performance developer library delivering normalized geographical metadata for 77 districts, 7 provinces, and municipal divisions of Nepal.
- **In-Depth Details:** info-nepal simplifies local address validation and geographical selector components in web and mobile applications. It offers fast, zero-dependency lookups, bilingual Devanagari & English mapping, and strict TypeScript ESM/CJS bundles.
- **Architecture Highlights:**
  - Zero runtime dependencies for maximum execution speed and zero security vulnerabilities
  - Full Devanagari and English script normalization with memoized index lookup
  - Tree-shakeable ESM and dual CJS bundle distribution for modern frameworks

---

### Project: HLS Audio Streaming Server Architecture
- **Category:** backend
- **Repository:** https://github.com/mondyfy/hls_demo
- **Tags:** Node.js, HLS, FFmpeg, Streaming, Express, Buffer Piping
- **Description:** High-performance HTTP Live Streaming (HLS) audio server leveraging Node.js streams and FFmpeg dynamic chunk transcoding.
- **In-Depth Details:** Demonstrates adaptive bitrate streaming of audio tracks, dynamic M3U8 playlist generation, and low-latency chunk buffering for scalable media distribution across varying client network conditions.
- **Architecture Highlights:**
  - Dynamic multi-bitrate audio segmenting via FFmpeg background workers
  - Custom HTTP byte-range request handler for smooth chunked media playback
  - Memory-efficient Node.js stream piping to minimize server memory footprint

---

### Project: Systems Programming & POSIX C Reference
- **Category:** opensource
- **Repository:** https://github.com/mondyfy/c-programming
- **Tags:** C, POSIX, System Programming, Memory Management, Valgrind
- **Description:** Comprehensive architectural tutorial repository for low-level memory allocation, pointer arithmetic, linked data structures, and POSIX system calls.
- **In-Depth Details:** A hands-on reference guide built for software engineers covering fundamental computer science principles, manual memory management, linked structures, sockets, and thread synchronization.
- **Architecture Highlights:**
  - Structured module progression covering low-level memory allocation (malloc/free)
  - Valgrind memory leak checks and Makefile compilation targets for strict C standards
  - Includes real-world algorithms and data structure benchmark tests

---

### Project: Kubernetes GitOps & Observability Stack
- **Category:** devops
- **Repository:** https://github.com/mondyfy
- **Tags:** Kubernetes, Helm, ArgoCD, OpenTelemetry, Terraform
- **Description:** Infrastructure-as-Code repository configuring Kubernetes cluster telemetry with Helm, ArgoCD, Prometheus, and OpenTelemetry.
- **In-Depth Details:** Declarative cluster manifest repository featuring GitOps deployment workflows, distributed tracing integration across microservices, and automated ingress SSL certificate renewal.
- **Architecture Highlights:**
  - GitOps continuous deployment pipeline with ArgoCD cluster state sync
  - OpenTelemetry collector daemonsets for log, metric, and trace correlation
  - Strict Kubernetes RBAC policies and automated TLS cert management

---

### Project: Feature Engineering & Data ETL Engine
- **Category:** datascience
- **Repository:** https://github.com/mondyfy
- **Tags:** Python, Pandas, Scikit-Learn, ETL, Data Pipelines
- **Description:** Scalable Python data processing pipeline for large datasets, vector feature engineering, and automated validation metrics.
- **In-Depth Details:** A robust Python data processing engine that handles stream ingestion, missing value imputation, statistical feature generation, and automated report generation for machine learning workflows.
- **Architecture Highlights:**
  - Distributed data extraction pipeline using Python multiprocessing workers
  - Scikit-Learn feature transformers with strict runtime schema validation
  - Automated PDF and HTML exploratory data analysis output generation

---

## Section 2: Work History & Speaking Record
### Senior Solution Architect / SRE Lead at Cherdung Info Tech (2021 - Present)
- **Location:** Kathmandu, Nepal | **Type:** Work
- **Overview:** Leading cloud infrastructure design, high-availability database cluster operations, microservices architecture, and SRE incident governance.
- **Key Achievements:**
  - Architected PostgreSQL HA cluster with Patroni and Etcd, maintaining 99.99% database uptime SLA across enterprise applications.
  - Engineered transition from legacy monolithic backends to containerized Kubernetes microservices managed via automated CI/CD.
  - Optimized query performance and connection pooling, boosting system request throughput by over 40%.
  - Established SRE operational procedures, observability dashboards (Prometheus/Grafana), and post-mortem incident reviews.
- **Technologies & Frameworks:** PostgreSQL, Patroni, Kubernetes, Docker, Go, Node.js, Prometheus, Terraform

### Software Engineer - Systems & Data at Fusemachines (2018 - 2021)
- **Location:** Kathmandu, Nepal | **Type:** Work
- **Overview:** Designed scalable data processing pipelines, backend microservices for AI platforms, and analytical data stores.
- **Key Achievements:**
  - Built automated ETL pipelines processing millions of daily data events for machine learning products.
  - Engineered high-performance RESTful and gRPC microservices in Python and Node.js.
  - Optimized database indexing and vector storage pipelines to cut model inference response latencies.
- **Technologies & Frameworks:** Python, Pandas, Scikit-Learn, PostgreSQL, FastAPI, AWS, Docker

### Conference Speaker - Relational Database Reliability at PostgreSQL Conference Nepal (2023)
- **Location:** Kathmandu, Nepal | **Type:** Speaking
- **Overview:** Delivered technical keynote on scaling PostgreSQL clusters, connection pool tuning, and failover automation in production.
- **Key Achievements:**
  - Presented empirical benchmarks comparing PgBouncer connection pooling against raw database connections.
  - Demonstrated real-time Patroni failover execution and active-standby database replication diagnostics.
- **Technologies & Frameworks:** PostgreSQL, Database Tuning, SRE, Patroni, Keynote Speaker

### Conference Speaker & Tech Contributor at WordCamp Nepal (2019 - 2022)
- **Location:** Nepal | **Type:** Speaking
- **Overview:** Spoke on modern web architecture, server-side caching strategies, and open-source software engineering.
- **Key Achievements:**
  - Conducted technical masterclasses on server performance optimization and custom extensibility architecture.
  - Mentored software engineers on open-source package distribution and technical governance.
- **Technologies & Frameworks:** Open Source, Web Architecture, Performance Optimization

---

## Section 3: Technical Skill Matrix
### Database Reliability & Storage
- PostgreSQL (Patroni, Replication, Tuning): Enterprise HA Clusters (Production Lead)
- PgBouncer & Connection Pooling: High-Concurrency Apps (Cluster Operator)
- Redis & Distributed Caching: Low-Latency Caching (Cluster Operator)
- pgBackRest & Disaster Recovery: Zero-Data-Loss Backups (Production Lead)

### Distributed Systems & Cloud
- Kubernetes & Helm: Multi-Cluster Deployments (Cluster Operator)
- Docker & Container Security: Microservice Delivery (Production Lead)
- Go (Golang) & Node.js / TS: High-Throughput Services (Production Lead)
- Terraform & AWS Cloud: Infrastructure as Code (Governance)

### SRE & Telemetry Governance
- Prometheus & Grafana: Metrics & Custom Alerting (Production Lead)
- OpenTelemetry & Tracing: Distributed Trace Correlation (Governance)
- Linux Administration & Bash: Kernel & POSIX Tuning (Production Lead)
- GitOps & CI/CD Pipelines: Automated Release Pipeline (Production Lead)

### Data Pipelines & Open Source
- NPM Package Engineering: 50k+ Public Downloads (Package Author)
- Python / Pandas / Scikit-Learn: ETL & Feature Extraction (Production Lead)
- FFmpeg & HLS Streaming: Adaptive Media Piping (Package Author)

---

## Section 4: Complete Technical Blog Posts
================================================================================
# Blog Post: Feature Branch Deployment Strategies for API Servers in GCP
URL: https://sandipbasnet.com.np/blogs/feature-branch-deployment-strategies-gcp
Date: Aug 10, 2026 | Category: GCP | Author: Sandip Basnet (Senior Software Engineer & SRE)
Tags: GCP, Cloud Run, CI/CD, Feature Branch, DevOps, API Servers, Docker, GitHub Actions

## Summary
How to design ephemeral preview environments for API servers using Google Cloud Run, Cloud Build, and GitHub Actions to isolate feature testing before production merge.

## Full Article Body
# Feature Branch Deployment Strategies for API Servers in GCP

In modern microservice architectures, testing features in isolation before merging into main branches is critical for ensuring release quality and developer velocity. Feature branch deployments (or ephemeral preview environments) allow engineers, QA testers, and product managers to interact with live endpoints for pull requests without polluting shared staging or production environments.

In this article, we explore how to leverage **Google Cloud Platform (GCP)**, specifically **Cloud Run**, **Cloud Build / GitHub Actions**, and **Cloud DNS / Secret Manager**, to build seamless, low-cost feature branch preview pipelines for backend API servers.

---

## The Architectural Blueprint

When a developer opens or updates a Pull Request (PR), the automation pipeline should:

1. **Trigger Container Build**: Build an immutable container image tagged with the short commit SHA (e.g., `gcr.io/my-project/api-server:sha-1234567`).
2. **Provision Ephemeral Cloud Run Revision**: Deploy the container to a dedicated GCP Cloud Run service named `api-preview-pr-142`.
3. **Inject Environment & Secrets**: Dynamically inject branch-specific environment variables and securely load database connection secrets from GCP Secret Manager.
4. **Generate Dynamic Preview URL**: Map a unique subdomain or provision an automatic Cloud Run default URL (e.g. `https://api-preview-pr-142-xyz-uc.a.run.app`).
5. **Post PR Feedback**: Automatically post the preview URL back to the GitHub PR comments via API bot.
6. **Automated Teardown**: Upon PR merge or closure, trigger a cleanup hook to delete the Cloud Run service, avoiding unnecessary cloud costs.

```
   [ Developer PR ]
          │
          ▼
   [ GitHub Actions / Cloud Build ]
          │
  ┌───────┴────────┐
  ▼                ▼
[ Build Image ]  [ Deploy Cloud Run Service ]
                   (e.g., api-pr-142)
                           │
                           ▼
                 [ Generate Preview URL ] ──► [ Comment on GitHub PR ]
```

---

## Key Benefits of GCP Cloud Run for Ephemeral Environments

- **Zero-Idle Cost**: Cloud Run scales down to zero instances when no traffic flows to a pull request preview. If a reviewer tests a PR for 15 minutes, you only pay for those 15 minutes of vCPU and memory execution.
- **Fast Startup (Cold Starts < 2s)**: Modern containerized Go, Node.js, or Rust services launch in under 2 seconds.
- **Isolated Revisions & IAM Security**: Each Cloud Run preview service is scoped under strict GCP IAM policies and service accounts.

---

## Implementation Walkthrough

### 1. GitHub Actions Pipeline (.github/workflows/preview-deploy.yml)

Here is a simplified workflow manifest executing on pull requests:

```yaml
name: Deploy PR Feature Branch Preview

on:
  pull_request:
    types: [opened, synchronize, reopened, closed]

env:
  GCP_PROJECT: my-gcp-project-id
  SERVICE_NAME: api-pr-${{ github.event.number }}

jobs:
  cleanup:
    if: github.event.action == 'closed'
    runs-on: ubuntu-latest
    steps:
      - name: Authenticate to GCP
        uses: google-github-actions/auth@v2
        with:
          credentials_json: ${{ secrets.GCP_SA_KEY }}

      - name: Delete Cloud Run Preview Service
        run: |
          gcloud run services delete ${{ env.SERVICE_NAME }} \
            --region=us-central1 \
            --quiet || true

  deploy:
    if: github.event.action != 'closed'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Authenticate to GCP
        uses: google-github-actions/auth@v2
        with:
          credentials_json: ${{ secrets.GCP_SA_KEY }}

      - name: Set up Cloud SDK
        uses: google-github-actions/setup-gcloud@v2

      - name: Build & Push Image
        run: |
          gcloud builds submit \
            --tag gcr.io/${{ env.GCP_PROJECT }}/${{ env.SERVICE_NAME }}:${{ github.sha }}

      - name: Deploy to Cloud Run
        run: |
          gcloud run deploy ${{ env.SERVICE_NAME }} \
            --image gcr.io/${{ env.GCP_PROJECT }}/${{ env.SERVICE_NAME }}:${{ github.sha }} \
            --region us-central1 \
            --platform managed \
            --allow-unauthenticated \
            --set-env-vars="NODE_ENV=preview,PR_ID=${{ github.event.number }}" \
            --min-instances=0 \
            --max-instances=2
```

---

## Managing Preview Data & Isolating State

One common challenge with feature branch previews is database state:

- **Isolated Schema Branching**: For relational databases like Cloud SQL (PostgreSQL), run migrations on an isolated preview schema (e.g. `schema_pr_142`) or leverage lightweight ephemeral database containers.
- **Mock External Services**: Route external third-party API dependencies (Payment gateways, Email senders) to sandbox endpoints using environment configuration overrides.

---

## Conclusion & Summary

Adopting ephemeral feature branch deployments in GCP transforms how teams review backend API changes. By combining Cloud Run's zero-scale compute with automated CI/CD pipelines, engineering teams achieve faster iteration loops, higher test confidence, and zero wasted cloud budget on idle preview environments.
================================================================================

================================================================================
# Blog Post: Mastering GCP Cost Saving: FinOps Strategies for Compute & GKE
URL: https://sandipbasnet.com.np/blogs/gcp-cost-saving-finops-strategies
Date: Jul 28, 2026 | Category: Cost Savings | Author: Sandip Basnet (Senior Software Engineer & SRE)
Tags: GCP, FinOps, Cost Savings, GKE, Committed Use, Spot VMs, Kubernetes, Billing

## Summary
Proven engineering strategies to reduce Google Cloud infrastructure expenditure by 30% to 50% using Committed Use Discounts, Spot VMs, GKE auto-scaling, and idle resource cleanup.

## Full Article Body
# Mastering GCP Cost Saving: FinOps Strategies for Compute & GKE

Cloud spending can easily spiral out of control without clear visibility, automated policies, and proactive capacity management. For organizations running heavy workloads on Google Cloud Platform (GCP), optimizing resource usage is an ongoing architectural practice rather than a one-time quarterly audit.

In this article, we cover tactical engineering strategies that reduced cloud compute costs by over 40% across production and staging GCP environments.

---

## 1. Leverage Spot VMs for Non-Production & Batch Workloads

Spot VMs (formerly Preemptible VMs) offer compute instances at up to a **60–91% discount** compared to standard compute pricing.

- **Ideal Use Cases**: CI/CD build agents, batch ETL data pipelines, fault-tolerant Kubernetes node pools, and staging clusters.
- **GKE Integration**: Use GKE node pools configured with Spot instances alongside cluster autoscaler and node affinity rules.

```hcl
# Example Terraform snippet for GKE Spot Node Pool
resource "google_container_node_pool" "spot_nodes" {
  name       = "spot-node-pool"
  cluster    = google_container_cluster.primary.name
  location   = "us-central1-a"
  node_count = 1

  node_config {
    preemptible  = true
    spot         = true
    machine_type = "e2-standard-4"

    labels = {
      "cloud.google.com/gke-spot" = "true"
    }

    taint {
      key    = "spot-instance"
      value  = "true"
      effect = "NO_SCHEDULE"
    }
  }
}
```

---

## 2. Implement Automated Off-Hours Downscaling for Staging

Non-production environments (Dev, Staging, QA) often run 24 hours a day, 7 days a week, despite only being used during business hours (40 hours/week). That means **~75% of non-prod compute cost is wasted**.

- **Solution**: Deploy a Cloud Scheduler job paired with Cloud Functions or Cloud Run to set GKE replica counts or stop non-essential Compute Engine instances at 7:00 PM and restart them at 7:00 AM on weekdays.

---

## 3. Utilize Flexible Committed Use Discounts (CUDs)

For predictable baseline workloads, Google Cloud's Committed Use Discounts offer 1-year or 3-year commitments in exchange for 37% to 55% cost reductions.

- **Flexible CUDs**: Provide baseline vCPU and RAM discounts across regions and instance series (E2, N2, N2D), ensuring you aren't locked into specific machine families as your architecture evolves.

---

## 4. Cloud SQL & Storage Lifecycle Optimization

- **Cloud SQL Idle Timeout**: Enable auto-pause or downsize staging database instances during off-peak windows.
- **GCS Storage Classes**: Define Object Lifecycle Management rules to transition logs, backups, and transient assets from Standard Storage to Nearline, Coldline, or Archive classes after 30 days.

---

## Summary Checklist for FinOps Success

1. Audit unattached persistent disks (PDs) and orphaned static IP addresses weekly.
2. Enable GCP Recommendations AI in Cloud Console for rightsizing machine types.
3. Configure GKE Horizontal Pod Autoscaler (HPA) and Vertical Pod Autoscaler (VPA).
================================================================================

================================================================================
# Blog Post: Zero-Idle Cost Serverless Architectures on Google Cloud Platform
URL: https://sandipbasnet.com.np/blogs/zero-idle-cost-serverless-architectures-gcp
Date: Jun 14, 2026 | Category: Serverless | Author: Sandip Basnet (Senior Software Engineer & SRE)
Tags: GCP, Serverless, Cloud Run, Cloud Functions, Eventarc, Pub/Sub, Architecture, Microservices

## Summary
Architecting event-driven microservices using Google Cloud Run, Cloud Functions, Eventarc, and Pub/Sub to pay only when your application code executes.

## Full Article Body
# Zero-Idle Cost Serverless Architectures on Google Cloud Platform

Modern cloud-native engineering prioritizes operational efficiency: zero server management, automatic scaling from 0 to thousands of instances, and true pay-per-use cost models.

Google Cloud Platform provides a rich suite of serverless primitives that, when orchestrated correctly, allow you to run full-stack products with **zero baseline idle cost**.

---

## Key Serverless Building Blocks in GCP

- **Cloud Run**: Containerized HTTP APIs & background workers (CPU & RAM consumed only during request execution)
- **Cloud Functions (2nd Gen)**: Lightweight event handlers & webhooks (Invocation count + execution duration)
- **Pub/Sub**: Decoupled message queuing & event streaming (Data volume published & delivered)
- **Eventarc**: Routing GCP audit logs & Cloud Storage events (Event delivery count)
- **Firestore / Datastore**: NoSQL serverless database (Reads, writes, deletes & storage volume)

---

## Event-Driven Architecture Example: Asynchronous Document Processing

Consider a background document processing pipeline triggered when a user uploads an image or PDF:

1. User uploads a document directly to a **Google Cloud Storage (GCS)** bucket using a signed URL.
2. **Eventarc** intercepts the `google.cloud.storage.object.v1.finalized` event and publishes a message to **Pub/Sub**.
3. A **Cloud Run** service containerized in Node.js/Python receives the event via HTTP push endpoint, extracts metadata, performs OCR or AI embedding, and saves the output to **Firestore**.
4. Once processing finishes, Cloud Run scales back down to zero instances.

```
  [ Client Upload ] ──► [ GCS Bucket ]
                             │ (Event: Object Created)
                             ▼
                        [ Eventarc ] ──► [ Pub/Sub Topic ]
                                                │
                                                ▼ (HTTP Push)
                                       [ Cloud Run Worker ] (Scales 0 ──► N)
                                                │
                                                ▼
                                      [ Firestore Database ]
```

---

## Cold Start Mitigations & Performance Optimization

While scaling down to zero is great for costs, cold starts can impact latency-sensitive APIs:

- **Use Lightweight Base Containers**: Prefer Minimal Alpine or Distroless images for Node.js, Go, or Python.
- **Initialize Heavy SDKs Globally**: Move database driver connections and GCP SDK initializations outside the handler function so warm containers reuse active sockets.
- **Cloud Run Minimum Instances**: For production endpoints requiring guaranteed latency under 100ms, set `--min-instances=1` only on production environments while keeping dev/staging at 0.
================================================================================

================================================================================
# Blog Post: Custom Domain Mapping and Automated SSL Management for GCP Cloud Run & Cloud Storage
URL: https://sandipbasnet.com.np/blogs/cloud-run-cloud-storage-custom-domain-mapping-gcp
Date: Jan 22, 2025 | Category: GCP | Author: Sandip Basnet (Senior Software Engineer & SRE)
Tags: GCP, Cloud Run, Cloud Storage, Custom Domain, SSL, DNS, DevOps

## Summary
Step-by-step guide to mapping apex domains and subdomains to Cloud Run microservices and Cloud Storage static assets with automated TLS certificate renewal.

## Full Article Body
# Custom Domain Mapping and Automated SSL Management for GCP Cloud Run & Cloud Storage

When launching production microservices on GCP Cloud Run or hosting static frontend assets on Google Cloud Storage (GCS), serving traffic under custom brand domain names (such as `api.mycompany.com` or `assets.mycompany.com`) is an essential branding and security requirement.

In this technical walkthrough, we cover both native **Cloud Run Domain Mapping** and **Global Load Balancer Domain Mapping** for Cloud Run services and GCS buckets, including zero-touch Google-managed SSL certificate provisioning.

---

## Option 1: Native Cloud Run Domain Mapping

For straightforward single-region services, GCP Cloud Run provides built-in domain mapping:

1. **Add Domain Mapping**: In Google Cloud Console or gcloud CLI, map your custom domain `api.example.com` to your target Cloud Run service.
2. **Domain Ownership Verification**: Add the requested Google TXT record to your Cloud DNS or external registrar (e.g. Cloudflare, Route53, Namecheap).
3. **Configure CNAME / ANAME Records**: Update your DNS zone with the CNAME records provided by GCP pointing to `ghs.googlehosted.com`.

```bash
# Create Domain Mapping via gcloud CLI
gcloud beta run domain-mappings create \
  --service=api-server \
  --domain=api.example.com \
  --region=us-central1
```

---

## Option 2: Cloud Storage (GCS) Custom Domain Mapping

To serve static web assets, images, or single-page apps directly from a GCS bucket under `cdn.example.com`:

1. **Name Bucket to Match Subdomain**: Create a bucket named strictly matching the target domain (e.g., `bucket name: cdn.example.com`).
2. **Set Bucket Access**: Grant `allUsers` the `Storage Object Viewer` role or restrict via Cloud CDN.
3. **DNS CNAME Entry**: Point `cdn.example.com` to `c.storage.googleapis.com` in your DNS manager.

---

## Automated TLS / SSL Certificate Provisioning

Both Cloud Run Domain Mappings and GCP Load Balancers automatically issue and renew 90-day Let's Encrypt / Google Trust Services TLS certificates. Once DNS records propagate (typically 5 to 15 minutes), HTTPS is enforced automatically with zero manual certificate key rotations required.
================================================================================

================================================================================
# Blog Post: GCP Cloud SQL Enterprise vs Enterprise Plus: High Availability, Multi-AZ & Read Replica Deep Dive
URL: https://sandipbasnet.com.np/blogs/gcp-cloud-sql-enterprise-vs-enterprise-plus-ha-comparison
Date: Dec 18, 2024 | Category: PostgreSQL & Databases | Author: Sandip Basnet (Senior Software Engineer & SRE)
Tags: GCP, Cloud SQL, PostgreSQL, Database, High Availability, Enterprise Plus, Read Replicas, SRE

## Summary
Comparing Cloud SQL Enterprise and Enterprise Plus editions for PostgreSQL and MySQL: uptime SLAs, maintenance downtime, Data Cache with NVMe SSDs, Multi-AZ failover, and read replicas.

## Full Article Body
# GCP Cloud SQL Enterprise vs Enterprise Plus: High Availability, Multi-AZ & Read Replica Deep Dive

When designing relational database infrastructure on GCP Cloud SQL for PostgreSQL or MySQL, database architects must choose between two distinct service tiers: **Cloud SQL Enterprise** and **Cloud SQL Enterprise Plus**.

Selecting the right tier impacts system availability SLAs, maintenance window downtime, transaction throughput, and monthly cloud costs. In this guide, we break down their architectural differences, Multi-AZ failover behaviors, and Read Replica strategies.

---

## Side-by-Side Architectural Comparison

- **Uptime Availability SLA**: Enterprise Edition provides **99.95% SLA**, whereas Enterprise Plus increases SLA to **99.99%**.
- **Maintenance Window Downtime**: Enterprise Edition updates cause typical maintenance downtime of 60 to 120 seconds. Enterprise Plus uses near-zero downtime maintenance reducing downtime to **under 10 seconds**.
- **SSD Data Cache**: Enterprise Plus includes an integrated local NVMe-based Data Cache tier that buffers reads, increasing query throughput up to **2x** and reducing tail latency for heavy read workloads.
- **Machine Instance Series**: Enterprise runs on standard N2 / E2 machine series, while Enterprise Plus leverages high-performance memory-optimized instance families (such as `m3-megamem`).

---

## Multi-AZ High Availability & Standby Replication

Both Cloud SQL editions support regional Multi-AZ High Availability:

- **Primary & Standby Pairing**: Writes are committed synchronously across primary (Zone A) and standby (Zone B) persistent disks.
- **Failover Time**: In Enterprise Plus, automated zonal failover completes faster due to optimized memory snapshotting and warm standby buffer pools.

---

## Read Replica Scaling Strategies

1. **Intra-Region Scaling**: Deploy up to 8 Read Replicas in the primary region to distribute HTTP GET database query load.
2. **Cross-Region Disaster Recovery**: Maintain a Cross-Region Read Replica in a secondary GCP region (e.g., `europe-west1`) for asynchronous backup and rapid regional failover promotion.

---

## Recommendation Matrix

- Choose **Cloud SQL Enterprise** for dev/staging environments, internal tools, and standard production workloads where 99.95% SLA and 60-second maintenance windows are acceptable.
- Choose **Cloud SQL Enterprise Plus** for tier-1 financial, e-commerce, or mission-critical enterprise applications requiring 99.99% uptime, near-zero maintenance downtime, and sub-millisecond data caching.
================================================================================

================================================================================
# Blog Post: Disaster Recovery Strategies (DRS) and Multi-Region Failover for GCP Cloud Run
URL: https://sandipbasnet.com.np/blogs/cloud-run-disaster-recovery-strategies-drs-gcp
Date: Nov 12, 2025 | Category: GCP | Author: Sandip Basnet (Senior Software Engineer & SRE)
Tags: GCP, Cloud Run, Disaster Recovery, Multi-Region, High Availability, DevOps, DRS

## Summary
Designing multi-region disaster recovery for Cloud Run applications using Global External HTTP(S) Load Balancing, active-passive failover, and latency-based routing.

## Full Article Body
# Disaster Recovery Strategies (DRS) and Multi-Region Failover for GCP Cloud Run

While Google Cloud Run provides managed zonal and regional resilience out of the box, enterprise SLA requirements demand zero-downtime multi-region disaster recovery strategies (DRS). A regional cloud outage or data center degradation should automatically shift application traffic without human intervention.

In this technical guide, we detail how to architect multi-region active-active and active-passive Cloud Run deployments using **Google Cloud Global External HTTP(S) Load Balancing**.

---

## Multi-Region Architecture Patterns

### 1. Active-Active Latency-Based Routing

In an active-active setup, identical Cloud Run services are deployed in two or more GCP regions (e.g. `us-central1` and `europe-west1`).

- **Global Load Balancing**: A single Global Anycast Virtual IP receives client requests and automatically routes users to the nearest Cloud Run region with available capacity.
- **Seamless Failover**: If one GCP region experiences an outage, the Global Load Balancer detects backend health probe failures within seconds and routes 100% of incoming traffic to the healthy standby region.

```
                          [ Global Anycast IP ]
                                    │
                     [ GCP Global Load Balancer ]
                                 ┌──┴──┐
                                 ▼     ▼
                       (Health Check / Latency)
                                 │     │
                ┌────────────────┘     └────────────────┐
                ▼                                       ▼
   [ Cloud Run: us-central1 ]              [ Cloud Run: europe-west1 ]
```

---

## Database Synchronization & Stateful Data Replication

Stateless Cloud Run containers failover instantly, but data consistency across regions requires planning:

- **Cloud Spanner**: Native global multi-region consistency for mission-critical transactional storage.
- **Cloud SQL Cross-Region Read Replicas**: Maintain a primary write database in region A and a read replica with automated failover promotion scripts in region B.

---

## Key Takeaways

1. Use Serverless Network Endpoint Groups (NEGs) to attach Cloud Run services to Global Load Balancers.
2. Set up Cloud Monitoring uptime checks and automated PagerDuty alerts for health probe degradation.
3. Conduct quarterly simulated region failover drills to validate DRS recovery time objectives (RTO < 30 seconds).
================================================================================

================================================================================
# Blog Post: Sub-Millisecond Caching for GCP Cloud Run with Cloud Memorystore for Redis
URL: https://sandipbasnet.com.np/blogs/gcp-cloud-memorystore-redis-caching-cloud-run
Date: Sep 05, 2025 | Category: Serverless | Author: Sandip Basnet (Senior Software Engineer & SRE)
Tags: GCP, Memorystore, Redis, Cloud Run, Serverless VPC, Caching, Performance

## Summary
Connecting serverless Cloud Run containers to private Cloud Memorystore Redis clusters using Serverless VPC Access connectors for ultra-fast response times.

## Full Article Body
# Sub-Millisecond Caching for GCP Cloud Run with Cloud Memorystore for Redis

High-throughput APIs hosted on GCP Cloud Run often encounter database query bottlenecks under heavy traffic spikes. Offloading repetitive read operations to an in-memory caching tier reduces database load and cuts API response times down to sub-milliseconds.

However, because Cloud Run services run outside private VPC networks by default, reaching a private **Cloud Memorystore (Redis / Valkey)** instance requires configuring **Serverless VPC Access**.

---

## Architecture Diagram

```
  [ Client Request ] ──► [ Cloud Run Container ]
                                │
                      (Serverless VPC Connector)
                                │
                ┌───────────────┴───────────────┐
                ▼                               ▼
     [ Cloud Memorystore ]           [ PostgreSQL / Cloud SQL ]
     (Sub-ms Redis Cache)            (Primary Relational DB)
```

---

## Setting Up Serverless VPC Access via gcloud CLI

1. Create a Serverless VPC Access connector in your GCP VPC network:

```bash
gcloud compute networks vpc-access connectors create redis-vpc-connector \
  --region=us-central1 \
  --subnet-project=my-gcp-project \
  --ip-cidr-range=10.8.0.0/28
```

2. Deploy your Cloud Run service connected to the VPC connector:

```bash
gcloud run deploy api-service \
  --image=gcr.io/my-project/api-service:latest \
  --region=us-central1 \
  --vpc-connector=redis-vpc-connector \
  --vpc-egress=private-ranges-only \
  --set-env-vars="REDIS_HOST=10.0.0.5,REDIS_PORT=6379"
```

---

## Caching Best Practices for Cloud Run

- **Connection Reuse**: Initialize the Redis client instance outside the handler function so warm Cloud Run instances reuse established TCP connections.
- **Cache Invalidation & TTL**: Enforce explicit Key Expiration (TTL) policies on all cached keys to prevent stale data accumulation.
================================================================================

================================================================================
# Blog Post: Asynchronous Task Queue Processing with GCP Cloud Tasks and Cloud Run
URL: https://sandipbasnet.com.np/blogs/async-background-task-processing-gcp-cloud-tasks-cloud-run
Date: May 19, 2025 | Category: Serverless | Author: Sandip Basnet (Senior Software Engineer & SRE)
Tags: GCP, Cloud Tasks, Cloud Run, Asynchronous Processing, Queue Management, Microservices

## Summary
Decoupling heavy background processing, managing API rate limits, and implementing exponential backoff retries using GCP Cloud Tasks and Cloud Run push handlers.

## Full Article Body
# Asynchronous Task Queue Processing with GCP Cloud Tasks and Cloud Run

When building web APIs, long-running operations such as sending transactional emails, generating PDF reports, or calling third-party APIs should never block the main HTTP request-response cycle. Executing synchronous long tasks leads to high API latency and client timeouts.

**Google Cloud Tasks** paired with **Cloud Run** push targets provides a serverless task queuing engine with built-in concurrency controls, rate limiting, and exponential retry policies.

---

## Key Components of Cloud Tasks Architecture

1. **Producer Service**: Your primary Cloud Run API receives client requests, dispatches a task payload to a Cloud Tasks queue within ~10ms, and responds immediately to the user.
2. **Cloud Tasks Queue**: Holds pending task payloads, enforcing rate limits (e.g. 50 tasks/sec) and scheduling task executions.
3. **Worker Service**: Cloud Tasks invokes a dedicated Cloud Run endpoint (`POST /tasks/process-email`) via HTTP push, passing authentication OIDC tokens.

```
  [ User ] ──► [ Frontend API ] ──(Enqueues Task)──► [ Cloud Tasks Queue ]
                      │                                      │
             (Fast HTTP 200 OK)                     (Controlled Push)
                      ▼                                      ▼
                [ Instant Response ]               [ Worker Cloud Run ]
```

---

## Node.js Producer Code Example

```typescript
import { CloudTasksClient } from '@google-cloud/tasks';

const client = new CloudTasksClient();

async function enqueueEmailTask(userEmail: string, templateId: string) {
  const parent = client.queuePath('my-gcp-project', 'us-central1', 'email-queue');
  
  const task = {
    httpRequest: {
      httpMethod: 'POST' as const,
      url: 'https://worker-api-xyz-uc.a.run.app/tasks/email',
      headers: { 'Content-Type': 'application/json' },
      body: Buffer.from(JSON.stringify({ userEmail, templateId })).toString('base64'),
      oidcToken: {
        serviceAccountEmail: 'cloud-tasks-sa@my-gcp-project.iam.gserviceaccount.com'
      }
    }
  };

  await client.createTask({ parent, task });
}
```

---

## Why Choose Cloud Tasks over Pub/Sub for Background Jobs

- **Targeted Scheduling**: Schedule tasks to execute at specific future timestamps (e.g. deliver notification in 2 hours).
- **Rate Limiting & Throttling**: Cap max concurrent task dispatches to prevent overwhelming downstream legacy APIs.
- **Deduplication & Retries**: Automatic configurable retries with exponential backoff intervals.
================================================================================

================================================================================
# Blog Post: Securing GCP Cloud Run with Global HTTPS Load Balancing & Cloud Armor WAF
URL: https://sandipbasnet.com.np/blogs/gcp-cloud-load-balancing-cloud-armor-waf-security
Date: Feb 14, 2025 | Category: DevOps & SRE | Author: Sandip Basnet (Senior Software Engineer & SRE)
Tags: GCP, Load Balancing, Cloud Armor, WAF, Security, Cloud Run, SSL, DevOps

## Summary
Protecting production Cloud Run services against DDoS attacks, SQL injection, and web exploits using GCP Global External HTTP(S) Load Balancers and Cloud Armor policies.

## Full Article Body
# Securing GCP Cloud Run with Global HTTPS Load Balancing & Cloud Armor WAF

Exposing default Cloud Run endpoints (`*.a.run.app`) directly to the public internet leaves backend applications exposed to automated bot scanners, volumetric DDoS attacks, and web application security vulnerabilities.

Placing a **Google Cloud Global External HTTP(S) Load Balancer** with **Cloud Armor Web Application Firewall (WAF)** in front of your Cloud Run services provides enterprise enterprise-grade perimeter protection, custom domain SSL management, and granular IP rate limiting.

---

## Security Architecture Flow

```
  [ Public Web Traffic ]
            │
            ▼
  [ GCP Global Anycast IP ]
            │
  [ Cloud Armor Security Policies ] ──(Filters SQLi, XSS, DDoS & Bots)
            │
  [ External HTTP(S) Load Balancer ]
            │ (Serverless NEG)
            ▼
  [ Cloud Run Service ] (Configured with --ingress=internal-and-cloud-load-balancing)
```

---

## Step-by-Step Security Hardening

### 1. Restrict Cloud Run Ingress Settings

Lock down the Cloud Run service so it only accepts traffic coming through the Cloud Load Balancer, ignoring direct access attempts to the `a.run.app` default hostname:

```bash
gcloud run services update api-service \
  --region=us-central1 \
  --ingress=internal-and-cloud-load-balancing
```

### 2. Configure Cloud Armor WAF Rules

Apply pre-configured OWASP Top 10 threat detection rules to block SQL injection (SQLi) and Cross-Site Scripting (XSS):

```bash
# Create Cloud Armor Security Policy
gcloud compute security-policies create cloud-run-waf-policy --description="WAF Rules for Cloud Run"

# Add OWASP SQLi Protection Rule
gcloud compute security-policies rules create 1000 \
  --security-policy=cloud-run-waf-policy \
  --expression="evaluatePreconfiguredExpr('sqli-v33-stable')" \
  --action="deny-403" \
  --description="Block SQL Injection attempts"
```

---

## Benefits

- **Google-Grade DDoS Defense**: Mitigate volumetric L3/L4 attacks at the edge before traffic hits your application.
- **Managed TLS Certificates**: Free automated SSL certificate generation and renewal for custom domains.
- **Geo-Blocking & Rate Limiting**: Limit request counts per IP address to stop brute-force attacks.
================================================================================

================================================================================
# Blog Post: High-Availability Database Topology for GCP Cloud SQL & PostgreSQL
URL: https://sandipbasnet.com.np/blogs/gcp-cloud-sql-postgresql-ha-topology
Date: May 22, 2026 | Category: PostgreSQL & Databases | Author: Sandip Basnet (Senior Software Engineer & SRE)
Tags: GCP, PostgreSQL, Cloud SQL, High Availability, Database, SRE, PgBouncer, Patroni

## Summary
Architecting high availability, read replicas, connection pooling with PgBouncer, and automated disaster recovery for PostgreSQL on Google Cloud.

## Full Article Body
# High-Availability Database Topology for GCP Cloud SQL & PostgreSQL

Relational database reliability is the cornerstone of mission-critical web applications. A database outage translates directly to application downtime, corrupted transactions, and revenue loss.

In this deep dive, we examine how to configure **GCP Cloud SQL for PostgreSQL** for 99.99% SLA availability, combining cross-AZ regional failover, PgBouncer connection pooling, and automated backup strategies.

---

## 1. Regional High Availability Configuration

Cloud SQL HA relies on a regional configuration with a Primary instance in a primary zone and a Standby instance in a secondary zone within the same GCP region.

- **Synchronous Replication**: Writes are committed to persistent disks across both zones simultaneously.
- **Automated Health Checks & Failover**: If the primary zone fails or experiences a hardware fault, Cloud SQL automatically redirects the regional IP address to the standby instance within ~60 seconds.

---

## 2. Connection Pooling with PgBouncer

High-concurrency serverless services (such as Cloud Run or Cloud Functions) can rapidly open hundreds of transient database connections, exhausting PostgreSQL's `max_connections` memory budget.

- **Solution**: Deploy a lightweight **PgBouncer** sidecar or dedicated GKE deployment using transaction-level connection pooling.
- **Benefits**: Reduces backend DB overhead, maintains low memory utilization, and allows thousands of concurrent microservices to reuse a pool of 20–50 established PostgreSQL backend sockets.

---

## 3. Read Replicas & Query Offloading

To prevent heavy analytical reporting or dashboard queries from locking OLTP transaction tables:

- Provision cross-region or intra-region **Read Replicas**.
- Route all HTTP `GET` requests or read-only database queries to read replica endpoints while reserving the primary instance exclusively for write transactions.
================================================================================

================================================================================
# Blog Post: Kubernetes GitOps & Helm Pipelines for GCP GKE Clusters
URL: https://sandipbasnet.com.np/blogs/gke-gitops-helm-deployments-gcp
Date: Apr 18, 2026 | Category: Kubernetes | Author: Sandip Basnet (Senior Software Engineer & SRE)
Tags: Kubernetes, GKE, GitOps, ArgoCD, Helm, GCP, DevOps, Workload Identity

## Summary
Declarative application continuous delivery on Google Kubernetes Engine (GKE) using ArgoCD, Helm, and GCP Workload Identity for zero-trust authorization.

## Full Article Body
# Kubernetes GitOps & Helm Pipelines for GCP GKE Clusters

GitOps has emerged as the industry standard for managing Kubernetes application lifecycle. By using Git repositories as the single source of truth for cluster state, engineering teams ensure auditable, reproducible deployments.

In this guide, we break down setting up **ArgoCD on GKE**, organizing Helm values for multi-environment clusters, and securing cluster access using **GCP Workload Identity**.

---

## GitOps Architecture Overview

- **Git Repository**: Stores declarative Kubernetes manifests & Helm values.
- **ArgoCD Operator**: Continuously monitors the repository and synchronizes GKE cluster state.
- **Workload Identity**: Binds Kubernetes Service Accounts directly to GCP IAM roles without requiring service account keys stored in secrets.

---

## Key Takeaways for Production GKE Deployment

1. Enable GKE Autopilot or VPC-native clusters for strict pod networking.
2. Enforce strict Helm template validation in pull requests using `helm lint`.
3. Configure automated rollback hooks in ArgoCD when health checks fail.
================================================================================

================================================================================
# Blog Post: GCP Cloud Security & Zero-Trust Architecture with Workload Identity
URL: https://sandipbasnet.com.np/blogs/gcp-workload-identity-zero-trust-security
Date: Mar 30, 2026 | Category: DevOps & SRE | Author: Sandip Basnet (Senior Software Engineer & SRE)
Tags: GCP, Cloud Security, Workload Identity, Zero Trust, IAM, DevOps, SRE

## Summary
Eliminating static service account JSON keys in GCP by adopting Workload Identity Federation for GKE, Cloud Run, and GitHub Actions.

## Full Article Body
# GCP Cloud Security & Zero-Trust Architecture with Workload Identity

Static service account JSON keys are one of the leading sources of security credentials leakage in cloud environments. Storing long-lived private keys in CI/CD variables or container images presents severe security risks.

Google Cloud **Workload Identity** solves this by establishing short-lived, cryptographically verified OpenID Connect (OIDC) tokens.

---

## How Workload Identity Works

1. External workload (e.g. GitHub Actions runner or GKE Pod) requests an OIDC token from its local provider.
2. Token is exchanged with GCP Security Token Service (STS) for a short-lived GCP IAM access token (valid 1 hour).
3. Zero long-lived secret keys stored in repository settings or configuration files.

---

## Benefits

- **Zero Credential Rotation Overhead**: Tokens expire automatically.
- **Fine-Grained Scope Binding**: Scope GCP permissions strictly to individual repositories or branches.
- **Complete Auditability**: All credential exchanges are logged in Cloud Logging.
================================================================================