Run Python in Google Sheets at Sub-Second Speed: Supercharging Google Apps Script with Cloud Run Sandboxes (Zero Idle Cost)

“…Senpai, I honestly don’t think I can finish compiling this spreadsheet by the end of the day…”

It was a late afternoon on an in-office day at our Sapporo branch. My junior colleague sat next to me, staring at her monitor on the verge of tears. When I peeked over her shoulder, I saw tens of thousands of rows of user event log data. She was desperately chaining together nested spreadsheet formulas to calculate correlations and generate charts, but the screen had completely frozen. Chrome displayed that dreaded popup: “Page Unresponsive.”

My core motto as a software engineer has always been: “Automate tedious manual work, and let’s all go home early!”
Getting stuck in the office and working late over slow spreadsheets is out of the question. Nothing beats wrapping up on time, stopping by Seicomart (the legendary convenience store lifesaver of Hokkaido) on the walk home, and picking up some piping-hot Hot Chef fried chicken and a 100-yen deli pasta tray to reward yourself for a productive day.

“Don’t worry! Let’s stop punishing Google Sheets with brute-force calculations and handle this the smart way in a fraction of a second.”

When it comes to Google Workspace automation, Google Apps Script (GAS) is the default tool of choice. Yet anyone who has pushed GAS to its limits has inevitably crashed into its painful boundaries: freezing spreadsheets on large datasets, inability to run modern data science libraries, and strict timeout limits.

In this guide, we will explore an architectural upgrade: combining Google Apps Script with Google Cloud Run Sandboxes to execute Python code from Google Sheets securely, with sub-second response times and zero idle cost.

Even if you feel intimidated by Python, Docker containers, or cloud infrastructure, there is no need to worry. We will break down every complex concept into friendly, everyday analogies, walking through each step just like sitting together at your desk!

📌 What You Will Learn in This Guide

  • The root causes behind slow, freezing Google Sheets and GAS timeouts
  • A beginner-friendly breakdown of Python, Pandas, Seaborn, and containers
  • How Cloud Run Sandboxes provide microVM isolation with $0 idle cost
  • Step-by-step code to run Pandas data aggregation and auto-generate Seaborn charts directly into your spreadsheet
  • How to build a custom formula =PY() to evaluate Python on the fly in spreadsheet cells

Chapter 1: Why Google Sheets Freezes: The 3 Critical Limits of Google Apps Script

Running directly in the browser without local environment setup, Google Apps Script (GAS) is fantastic for everyday workflow automation, such as sending emails via Gmail or updating rows from Google Forms.

However, when your datasets grow into tens of thousands of rows or require serious statistical modeling, you hit three hard ceilings.

Limit 1: JavaScript Only (No Native Python, Pandas, or Seaborn)

Python is the undisputed king of data analysis, scientific computing, and machine learning. In contrast, GAS runs exclusively on a JavaScript (V8) runtime.
This means you cannot natively leverage battle-tested data manipulation powerhouses like Pandas or publication-ready statistical plotting libraries like Seaborn directly inside Sheets.

Limit 2: Strict Execution Timeouts

Google enforces strict runtime quotas to keep shared Workspace infrastructure responsive:

  • Standard script triggers / functions: Hard cap of 6 minutes
  • Custom spreadsheet formulas (in-cell functions): Strict cap of 30 seconds

Looping through tens of thousands of rows in JavaScript easily exceeds these thresholds, resulting in the dreaded red banner: Exceeded maximum execution time.

Limit 3: Security Risks of Running Untrusted or AI-Generated Code

Many teams now want LLMs (like Gemini or ChatGPT) to generate data-transformation scripts dynamically. However, using eval() inside Google Apps Script to run dynamic code is a dangerous anti-pattern. If a generated script contains malicious logic, it could compromise sensitive Google Drive files or leak corporate sheet contents.

You might ask: “Why not host a Python container on a traditional cloud VM or container service?”
While viable, keeping dedicated VMs running 24/7 incurs continuous idle costs. More importantly, allowing arbitrary AI-generated code inside a standard container poses serious security risks, such as Server-Side Request Forgery (SSRF) targeting cloud metadata servers to extract service account credentials.

This is where Cloud Run Sandboxes changes the game.

Chapter 2: Beginner-Friendly Tech Primer: Core Concepts Simplified

Before writing code, let’s quickly demystify the core building blocks with simple analogies. Once you understand what each component does, the architecture clicks into place naturally.

1. Python = The All-in-One Swiss Army Knife

A clean, readable programming language beloved worldwide by data scientists, web developers, and AI researchers alike. It is simple to learn yet capable of heavy lifting.

2. Pandas = A Spreadsheet Engine on Jet Fuel

An open-source Python library designed specifically for tabular data manipulation. Operations that lock up Google Sheets for several minutes—such as filtering, grouping, and calculating correlation matrices across 100,000 rows—run in less than 50 milliseconds in Pandas.

3. Matplotlib & Seaborn = Professional Graphic Designers

Python’s premier visualization libraries:

  • Matplotlib: The foundational drafting table that constructs axes, plots, and layout geometry.
  • Seaborn: The art director that applies gorgeous color palettes and statistical themes. It turns complex correlation tables into elegant, publication-quality heatmaps with a single line of code.

4. Docker & Containers = A Standardized Bento Box

A container bundles your application, runtime, and third-party libraries into a single portable package. It eliminates the “it worked on my machine” headache by ensuring code runs identically on your laptop and in the cloud.

5. FastAPI = A Lightning-Fast Order Counter

A modern, high-performance Python web framework for building APIs. It receives incoming calculation requests from Google Apps Script and dispatches responses back in milliseconds.

6. Cloud Run Sandboxes = An Unbreakable, Reinforced Glass Capsule

This is the centerpiece technology. Google Cloud Run Sandboxes leverage lightweight gVisor micro-virtualization to spin up ephemeral, zero-trust isolation boundaries inside your container in single-digit milliseconds.

[ Traditional Container Execution ]
Untrusted script runs directly in the host container.
⚠️ Risk: Host environment variables, file tokens, and metadata server (169.254.169.254) are exposed!

[ Cloud Run Sandboxes (gVisor microVM) ]
Container creates an isolated, tamper-proof glass room on demand!
✅ Cloud credentials, metadata server, and host environment variables are strictly blocked.
✅ Outbound network access (egress) is blocked by default to prevent data exfiltration.
✅ File writes are restricted to temporary memory (tmpfs) that dissolves instantly after execution.
✅ Scales down to 0 instances when idle: 100% serverless, zero idle infrastructure cost!

This means you can execute arbitrary, dynamic data-processing scripts with complete peace of mind, all while paying strictly for the few hundred milliseconds of compute time you consume.

Chapter 3: System Architecture: The Online Kitchen Order Analogy

To visualize how data moves between Google Sheets and Cloud Run, think of the system as an on-demand culinary delivery service:

[ STEP 1: ORDER ] You (Google Sheets / GAS)
Click a button! "Please analyze this dataset and generate a correlation heatmap!"
│
▼ (Secure HTTPS Request with Google IAM Token)
[ STEP 2: FRONT DESK ] Cloud Run Service (FastAPI)
Verifies your Google IAM identity: "Authorized company user confirmed. Routing to the kitchen!"
│
▼
[ STEP 3: COOKING ] Reinforced Glass Kitchen (Sandbox Subprocess)
Python, Pandas, and Seaborn crunch numbers and render the chart in under 300 ms!
│
▼ (Returns Base64 image payload)
[ STEP 4: DELIVERY ] Your Spreadsheet Screen
The finished, high-resolution chart pops up right beside your data table!

This architecture delivers three major benefits:

  • Your local browser never freezes, because heavy matrix operations run entirely in the cloud.
  • Sub-second response times (300–500 ms) make the user experience feel immediate.
  • Total process isolation guarantees that unvetted scripts cannot breach your cloud infrastructure.

Chapter 4: Backend Setup: Deploying Cloud Run Sandboxes with FastAPI

Let’s build the backend. Create a new directory on your local machine containing the following three files.

1. requirements.txt

List the required Python packages for web serving and data science:

fastapi>=0.110.0
uvicorn>=0.28.0
pydantic>=2.0.0
pandas>=2.2.0
numpy>=1.26.0
matplotlib>=3.8.0
seaborn>=0.13.0

2. main.py

This FastAPI application accepts incoming Python code and dispatches it into an isolated gVisor micro-sandbox using the sandbox do -- CLI launcher:

import subprocess
import tempfile
import os
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI(title="GAS-CloudRun-Sandbox")

class ExecuteRequest(BaseModel):
code: str # Python code payload to run
timeout_sec: int = 10 # Execution timeout in seconds

@app.get("/")
def health_check():
return {"status": "healthy", "message": "Cloud Run Sandbox is ready!"}

@app.post("/run")
def run_code(request: ExecuteRequest):
"""
Executes submitted Python code securely inside a Cloud Run Sandbox subprocess.
"""
# 1. Write the submitted script to an ephemeral local file
with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as tmp:
tmp.write(request.code)
tmp_path = tmp.name

try:
# 2. Execute via the sandbox launcher: "sandbox do -- python3 "
# This isolates execution from host credentials, metadata servers, and egress networks.
cmd = ["sandbox", "do", "--", "python3", tmp_path]

result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=request.timeout_sec
)

# 3. Return structured execution results
return {
"success": result.returncode == 0,
"stdout": result.stdout,
"stderr": result.stderr,
"exit_code": result.returncode
}

except subprocess.TimeoutExpired:
raise HTTPException(status_code=408, detail="Script execution timed out.")
except Exception as e:
raise HTTPException(status_code=500, detail=f"Internal Server Error: {str(e)}")
finally:
# 4. Clean up temporary files immediately
if os.path.exists(tmp_path):
os.remove(tmp_path)

3. Dockerfile

Use a lightweight Debian-based Python image and package your dependencies:

FROM python:3.11-slim

RUN apt-get update && apt-get install -y --no-install-recommends \
bash \
curl \
&& rm -rf /var/lib/apt/lists/*

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY main.py .

ENV PORT=8080
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080"]

4. Deploying to Cloud Run

Open your terminal and deploy your container using the gcloud CLI. The essential flag here is --sandbox-launcher:

gcloud beta run deploy gas-python-sandbox \
--source . \
--region asia-northeast1 \
--execution-environment gen2 \
--sandbox-launcher \
--no-allow-unauthenticated
  • --execution-environment gen2: Enables Cloud Run second-generation execution environment (required).
  • --sandbox-launcher: Crucial! Injects the native sandbox orchestration runtime and sandbox CLI into your container environment.
  • --no-allow-unauthenticated: Enforces Google IAM authentication, blocking public unauthorized traffic.

Once deployment finishes, copy your generated service URL (e.g., https://gas-python-sandbox-xxxxxx.a.run.app). You will paste it into your Google Apps Script in the next step.

Chapter 5: Frontend Integration: Google Sheets & Google Apps Script (GAS)

Now let’s connect our spreadsheet to Cloud Run.

For our practical example, let’s use a dataset inspired by my personal hobby: tracking my walking workouts around Sapporo (strolling through Odori Park, Nakajima Park, and along the scenic Toyohira River). Imagine your fitness tracker logs dates, step counts, ambient outdoor temperatures, and calories burned into a sheet.

Paste the following sample data into cells A1:D6 in your active sheet:

DateStepsTemp (C)Calories (kcal)
10/011250018.5480
10/02820016.0310
10/031540014.2590
10/04610019.1240
10/051890012.8710

We want to analyze whether colder temperatures correlate with higher walking intensity and calorie expenditure, calculate a correlation matrix in Pandas, generate an annotated Seaborn heatmap, and insert the graphic directly into our sheet.

Adding the Google Apps Script Code

In your spreadsheet, navigate to Extensions > Apps Script, remove any default boilerplate, and paste the following script:

/**
* Configuration: Replace with your actual Cloud Run service URL
*/
const CLOUD_RUN_URL = "https://gas-python-sandbox-xxxxxx.a.run.app/run";

/**
* Invokes the Cloud Run Sandbox API with Google Identity Token Authentication
*/
function callSandboxAPI(pythonScript) {
// Retrieve the OIDC identity token for the current Google Workspace user/service
const idToken = ScriptApp.getIdentityToken();

const payload = {
code: pythonScript,
timeout_sec: 15
};

const options = {
method: "post",
contentType: "application/json",
headers: {
Authorization: `Bearer ${idToken}`
},
payload: JSON.stringify(payload),
muteHttpExceptions: true
};

const response = UrlFetchApp.fetch(CLOUD_RUN_URL, options);
const status = response.getResponseCode();
const responseText = response.getContentText();

if (status !== 200) {
throw new Error(`API Request Error (HTTP ${status}): ${responseText}`);
}

const result = JSON.parse(responseText);
if (!result.success) {
throw new Error(`Python Runtime Error:\n${result.stderr}`);
}

return result.stdout;
}

/**
* Creates a custom menu in Google Sheets upon opening the file
*/
function onOpen() {
const ui = SpreadsheetApp.getUi();
ui.createMenu("🚀 Advanced Analytics")
.addItem("Generate Seaborn Correlation Heatmap", "generateCorrelationHeatmap")
.addToUi();
}

/**
* Sends spreadsheet data to Python and renders a Seaborn heatmap back into the sheet
*/
function generateCorrelationHeatmap() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();

// Extract all data from the active range
const data = sheet.getDataRange().getValues();
if (data.length < 2) {
SpreadsheetApp.getUi().alert("Insufficient data points for correlation analysis.");
return;
}

// Convert raw 2D array to serialized JSON
const jsonData = JSON.stringify(data);

// Python processing script
const pythonScript = `
import json
import io
import base64
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# 1. Load tabular JSON into a Pandas DataFrame
raw_data = ${jsonData}
headers = raw_data[0]
rows = raw_data[1:]
df = pd.DataFrame(rows, columns=headers)

# Parse numeric columns
numeric_cols = [c for c in df.columns if c != "Date"]
for c in numeric_cols:
df[c] = pd.to_numeric(df[c], errors='coerce')

# 2. Compute correlation matrix instantaneously
corr = df[numeric_cols].corr()

# 3. Render a styled Seaborn heatmap
plt.figure(figsize=(6, 4.5))
sns.set_theme(style="white")
heatmap = sns.heatmap(
corr,
annot=True,
cmap="coolwarm",
fmt=".2f",
linewidths=.5,
cbar=True
)
plt.title("Walking Activity Correlation", fontsize=14, pad=12)
plt.tight_layout()

# 4. Encode plot buffer to Base64 string
buffer = io.BytesIO()
plt.savefig(buffer, format='png', dpi=120)
buffer.seek(0)
img_base64 = base64.b64encode(buffer.read()).decode('utf-8')
plt.close()

# Print base64 string to stdout for capture
print(img_base64)
`;

SpreadsheetApp.getActiveSpreadsheet().toast("Crunching data in Cloud Run Sandbox...", "Processing", 5);

try {
// Call Cloud Run and retrieve Base64 encoded PNG
const base64Image = callSandboxAPI(pythonScript).trim();

// Decode Base64 string to Image Blob
const decodedBytes = Utilities.base64Decode(base64Image);
const blob = Utilities.newBlob(decodedBytes, "image/png", "correlation_heatmap.png");

// Insert image into cell F2
sheet.insertImage(blob, 6, 2);

SpreadsheetApp.getUi().alert("✨ Correlation heatmap generated successfully!");
} catch (err) {
SpreadsheetApp.getUi().alert(`Execution Failed:\n${err.message}`);
}
}

Running the Script

Save your script and reload your Google Sheet in your browser (press F5). You will notice a new menu appear on the toolbar: “🚀 Advanced Analytics”.

Click “🚀 Advanced Analytics” > “Generate Seaborn Correlation Heatmap”. (Note: On your first execution, Google will prompt you with an authorization modal to grant script permissions).

Within seconds, a high-resolution, color-graded correlation heatmap automatically inserts itself right next to your spreadsheet table!

My colleague’s jaw dropped: “Wait… are you serious? Is this actually Google Sheets?! Python plotted that in real time?!” That moment of pure relief on a teammate’s face is what making DX breakthroughs is all about.

Chapter 6: Evaluating Formulas in Cells: The Custom “=PY()” Function

Beyond UI buttons, you can also write Python expressions directly inside spreadsheet cells just like native functions (=SUM() or =VLOOKUP()).

Append this custom function to the bottom of your Apps Script editor:

/**
* Evaluates Python expressions directly inside Google Sheets cells.
* @param {string} formula Python expression to evaluate (e.g., "2 ** 10" or "sum([10, 20, 30])")
* @return Evaluated result string
* @customfunction
*/
function PY(formula) {
if (!formula) return "";

const script = `
try:
result = eval("""${formula}""")
print(result)
except Exception as e:
print(f"Error: {e}")
`;

try {
const output = callSandboxAPI(script);
return output.trim();
} catch (e) {
return `Error: ${e.message}`;
}
}

Once saved, click any empty cell in your spreadsheet and type:

=PY("import math; math.factorial(15)")

Hit Enter, and in just 300 to 500 milliseconds, the cell updates with:

1307674368000

Because code evaluation runs inside a sandboxed microVM container, users cannot escape the runtime or harm underlying cloud servers, making it completely safe to share across your organization.

Chapter 7: Senior Engineer Tips: 5 Production Gotchas & Best Practices

Here are five key takeaways and operational considerations learned from deploying sandboxed workloads in production.

Tip 1: Handling Cold Starts Gracefully

Cloud Run automatically scales to 0 instances when inactive to eliminate hosting costs. Consequently, the very first request after an idle period incurs a brief container initialization delay of approximately 2 to 3 seconds. Subsequent requests maintain blazing-fast 300 ms response cycles.
If your organization demands zero initial latency at 9:00 AM, configure a single warm baseline instance using --min-instances 1.

Tip 2: Ephemeral File Systems (No Persistent Local Disk)

The file system inside sandbox do -- is temporary memory (tmpfs) that vanishes the instant the subprocess terminates. Never rely on local storage for persistence. Always return generated plots as Base64-encoded strings or stream binary assets directly to Google Drive or Cloud Storage.

Tip 3: Outbound Egress is Blocked by Default

To defend against data exfiltration, Cloud Run Sandboxes block outbound internet connectivity from sandboxed child processes by default. If your script must fetch external market data or public APIs, enable egress explicitly via sandbox launch configuration. For internal spreadsheet math, keeping egress disabled is the most secure posture.

Tip 4: Pre-bake Packages in Your Dockerfile

Dynamic package installation (e.g., executing pip install at runtime) is restricted inside the sandbox boundary. Ensure all data science, computer vision, or machine learning libraries (such as Scikit-learn, SciPy, or OpenCV) are declared in requirements.txt during your container image build.

Tip 5: The “Reserved Seat” Travel Analogy

Whenever I travel to Tokyo for technical conferences or concerts, I fly out of New Chitose Airport. When returning to Sapporo on the JR Rapid Airport train, I always pay extra to reserve a “u-Seat” car. That small decision buys a peaceful, isolated personal workspace completely insulated from the crowded main cars. In many ways, Cloud Run Sandboxes give your backend that exact same guarantee: guaranteed process isolation, zero interference, and total peace of mind!

Conclusion: Automate Smartly and Reclaim Your Time!

By pairing Google Apps Script with Cloud Run Sandboxes, you unlock the best of both worlds:

  • The familiar, accessible UX of Google Sheets for everyday business users
  • The unbridled computational power of Python (Pandas, NumPy, Seaborn)
  • Enterprise-grade, zero-trust security via gVisor microVM process isolation
  • $0 idle maintenance cost thanks to true scale-to-zero serverless architecture

Deploying this hybrid pattern turns fragile spreadsheets into enterprise-grade data platforms while eliminating manual bottlenecks.

As for my colleague? She finalized her analysis, shut down her laptop right at 6:00 PM, and headed home with a smile. I clocked out right on time alongside her, grabbing some hot Seicomart fried chicken and Daifuku on my way back to an evening of swimming and tech tinkering.

Automate the tedious busywork, safeguard your infrastructure, and reclaim your personal time. Give Cloud Run Sandboxes and Google Apps Script a try in your next Workspace project!