Bayangkan punya API yang bisa handle request tanpa perlu sewa server 24/7. Bayar hanya saat kode dijalankan, bukan saat idle. Itulah konsep serverless functions.
Helipod mendukung serverless functions — kamu bisa menjalankan kode tanpa mengelola server, container, atau infrastructure. Tulis fungsi, deploy, dan biarkan sistem mengelola sisanya.
Apa Itu Serverless Functions?
Serverless functions adalah unit kode yang dijalankan sebagai response terhadap event:
- HTTP request — API endpoint
- Cron schedule — tugas terjadwal
- Event trigger — dari service lain
- Webhook — dari layanan eksternal
Kelebihannya:
- Tidak perlu server — tidak perlu sewa VPS
- Bayar saat pakai — tidak ada biaya saat idle
- Auto scale — scale otomatis sesuai traffic
- Fokus kode — tidak perlu urus infrastructure
Kapan Perlu Serverless?
| Use Case | Contoh |
|---|---|
| API endpoints | REST API, GraphQL |
| Webhooks | Payment callback, notification handler |
| Scheduled tasks | Cleanup data, generate report |
| Image processing | Resize, watermark, convert |
| Auth callbacks | OAuth redirect handler |
Cara Deploy Serverless Functions
Langkah 1: Buat Service
- Buka halaman project di Helipod
- Klik New Service
- Pilih Function atau Serverless
- Pilih runtime (Node.js, Python, Go, dll)
- Klik Create
Langkah 2: Tulis Kode
Buat file function sesuai runtime yang dipilih:
Node.js:
// api/hello.js
export default function handler(req, res) {
res.status(200).json({
message: 'Hello from Helipod!',
timestamp: new Date().toISOString(),
});
}
Python:
# api/hello.py
import json
from datetime import datetime
def handler(request):
return {
'statusCode': 200,
'body': json.dumps({
'message': 'Hello from Helipod!',
'timestamp': datetime.now().isoformat()
})
}
Langkah 3: Deploy
Push kode ke repository yang terhubung, atau upload langsung dari dashboard.
Contoh Use Cases
1. REST API
// api/users.js
export default async function handler(req, res) {
const { method } = req;
switch (method) {
case 'GET':
const users = await db.query('SELECT * FROM users');
return res.status(200).json(users);
case 'POST':
const { name, email } = req.body;
await db.query('INSERT INTO users (name, email) VALUES (?, ?)', [name, email]);
return res.status(201).json({ message: 'User created' });
default:
return res.status(405).json({ error: 'Method not allowed' });
}
}
2. Webhook Handler
// api/webhook/payment.js
import crypto from 'crypto';
export default async function handler(req, res) {
const signature = req.headers['x-signature'];
const payload = JSON.stringify(req.body);
// Verify signature
const expected = crypto
.createHmac('sha256', process.env.WEBHOOK_SECRET)
.update(payload)
.digest('hex');
if (signature !== expected) {
return res.status(401).json({ error: 'Invalid signature' });
}
// Process payment
const { order_id, status } = req.body;
await db.query('UPDATE orders SET status = ? WHERE id = ?', [status, order_id]);
return res.status(200).json({ received: true });
}
3. Scheduled Task
// jobs/cleanup.js
export default async function handler(req, res) {
// Hapus data yang lebih dari 30 hari
await db.query(`
DELETE FROM logs
WHERE created_at < NOW() - INTERVAL 30 DAY
`);
// Generate laporan
const stats = await db.query(`
SELECT COUNT(*) as total,
DATE(created_at) as date
FROM logs
GROUP BY DATE(created_at)
`);
return res.status(200).json({
deleted: 'old logs',
stats
});
}
4. Image Processing
// api/resize.js
import sharp from 'sharp';
export default async function handler(req, res) {
const { imageUrl, width = 800 } = req.body;
// Fetch image
const response = await fetch(imageUrl);
const buffer = await response.arrayBuffer();
// Resize
const resized = await sharp(Buffer.from(buffer))
.resize(width)
.webp({ quality: 80 })
.toBuffer();
res.setHeader('Content-Type', 'image/webp');
res.send(resized);
}
Environment Variables
Serverless functions bisa mengakses environment variables yang di-set di Helipod:
export default async function handler(req, res) {
const apiKey = process.env.API_KEY;
const dbUrl = process.env.DATABASE_URL;
// Gunakan variables
const data = await fetchData(apiKey, dbUrl);
res.status(200).json(data);
}
Untuk panduan environment variables, baca: Environment Variables di Helipod
Monitoring Serverless Functions
Dari Dashboard
Pantau invocation count, duration, dan error rate dari tab Metrics.
Dari Heli Crew
Kamu → "cek metrik function api/payment-webhook"
Heli Crew → "Function Metrics:
- Invocations (24h): 1,234
- Avg Duration: 145ms
- Error Rate: 0.2%
- Cold Starts: 12%"
Untuk penjelasan lengkap monitoring, baca: Monitoring dan Logs Real-time
Serverless vs Container
| Serverless | Container | |
|---|---|---|
| Scaling | Otomatis (instant) | Otomatis (per pod) |
| Cold start | Ada (ms-detik) | Tidak ada |
| Biaya | Per invocation | Per waktu |
| Duration limit | Biasanya 30 detik | Tidak ada limit |
| State | Stateless | Bisa stateful |
| Use case | API, webhook, tasks | Long-running apps |
Best Practices
1. Keep Functions Small
Fokus satu fungsi untuk satu tugas. Jangan buat function yang terlalu kompleks.
2. Handle Cold Starts
Cold start terjadi saat function pertama kali dijalankan. Untuk mengurangi dampaknya:
- Minimalkan dependencies
- Gunakan connection pooling
- Pertimbangkan warming strategies
3. Gunakan Environment Variables
Jangan hardcode secrets. Simpan di environment variables Helipod.
4. Monitor Error Rate
Setup alert untuk error rate yang tinggi. Gunakan Heli Crew untuk cek cepat.
5. Test Locally
Gunakan tools lokal untuk test sebelum deploy:
- Node.js:
vercel devataunetlify dev - Python:
pytestdengan local handler
Mulai Sekarang
Daftar gratis di helipod.io. Buat service function, tulis kode, dan deploy dalam hitungan menit.
Butuh bantuan? Hubungi support@helipod.id atau bergabung di komunitas hangar.helipod.io.
Baca juga:
- Environment Variables di Helipod — cara set konfigurasi
- Monitoring dan Logs Real-time — pantau aplikasi dari dashboard
- CI/CD dengan GitLab — auto deploy setiap push