
Cloud
Learning Level
Google Cloud provides automatic scaling capabilities that adjust resources based on demand. Understanding scaling patterns and optimization techniques ensures your applications remain responsive and cost-effective under varying load.
By the end of this lesson, you'll understand:
| Type | Details |
|---|---|
| Horizontal | Add more instances (Recommended) |
| Vertical | Make instances larger (Limited) |
# Create instance group with autoscaling
gcloud compute instance-groups managed create web-server-group \
--base-instance-name=web-server \
--template=web-server-template \
--size=2 \
--zone=us-central1-a
# Set autoscaling policy
gcloud compute instance-groups managed set-autoscaling web-server-group \
--max-num-replicas=10 \
--min-num-replicas=2 \
--target-cpu-utilization=0.65 \
--zone=us-central1-agcloud run deploy my-service \
--image gcr.io/my-project/my-image \
--max-instances=100 \
--min-instances=1 \
--memory 512Mi \
--cpu 1Custom scaling with Dockerfile:
FROM node:18-alpine
WORKDIR /app
COPY . .
# Multi-stage build for smaller image
FROM node:18-alpine
COPY --from=0 /app/dist ./dist
COPY --from=0 /app/node_modules ./node_modules
EXPOSE 3000
CMD ["node", "dist/server.js"]# Create health check
gcloud compute health-checks create http http-check \
--request-path=/health \
--port=3000
# Create backend service
gcloud compute backend-services create my-backend \
--health-checks=http-check \
--protocol=HTTP \
--enable-cdn
# Add instances to backend
gcloud compute backend-services add-backends my-backend \
--instance-group=web-server-group \
--zone=us-central1-a
# Create URL map
gcloud compute url-maps create my-lb \
--default-service=my-backend
# Create HTTP proxy
gcloud compute target-http-proxies create my-proxy \
--url-map=my-lb
# Create forwarding rule
gcloud compute forwarding-rules create my-fw-rule \
--global \
--target-http-proxy=my-proxy \
--address=my-static-ip \
--ports=80Node.js with Redis:
const redis = require('redis');
const client = redis.createClient({
host: 'redis-server',
port: 6379
});
async function getCachedUser(userId) {
const cacheKey = `user:${userId}`;
// Try cache first
const cached = await client.get(cacheKey);
if (cached) {
return JSON.parse(cached);
}
// Fetch from database
const user = await db.query('SELECT * FROM users WHERE id = ?', [userId]);
// Store in cache (expire after 1 hour)
await client.setex(cacheKey, 3600, JSON.stringify(user));
return user;
}App configuration:
app.use((req, res, next) => {
// Cache static assets for 1 year
if (req.url.startsWith('/static/')) {
res.set('Cache-Control', 'public, max-age=31536000, immutable');
}
// Cache API responses for 5 minutes
else if (req.url.startsWith('/api/')) {
res.set('Cache-Control', 'public, max-age=300');
}
// Don't cache HTML
else {
res.set('Cache-Control', 'public, max-age=0, must-revalidate');
}
next();
});Node.js:
const pool = mysql.createPool({
connectionLimit: 10,
waitForConnections: true,
queueLimit: 0,
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME
});// Bad: N+1 query problem
const users = await db.query('SELECT * FROM users');
for (const user of users) {
const posts = await db.query('SELECT * FROM posts WHERE user_id = ?', [user.id]);
user.posts = posts;
}
// Good: Single query with JOIN
const users = await db.query(`
SELECT users.*, posts.*
FROM users
LEFT JOIN posts ON users.id = posts.user_id
`);# CPU utilization
gcloud monitoring read-time-series \
--filter='metric.type=compute.googleapis.com/instance/cpu/utilization'
# Network I/O
gcloud monitoring read-time-series \
--filter='metric.type=compute.googleapis.com/instance/network/received_bytes_count'Learn about Cloud Trace for detailed performance analysis, or explore optimization techniques for your specific application.
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward