2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

30日間で理解する GCP for AWSエンジニア - 実践ブログシリーズ - 10日目: LambdaとCloud Functions:イベント駆動型サーバーレスの実装

2
Last updated at Posted at 2025-08-26

【AWS経験者向け】LambdaとCloud Functions:サーバーレス関数を徹底比較

はじめに:サーバーレスコンピューティングの現在地

皆さん、こんにちは!「30日間でGCPをマスターするAWSエンジニアの挑戦」シリーズ、10日目へようこそ。

AWS Lambda は、2014年のリリース以来、サーバーレスコンピューティングの代名詞として多くの開発者に愛用されてきました。イベント駆動型の実行モデルにより、EC2インスタンスの管理から解放され、純粋にビジネスロジックに集中できる革新的なサービスです。

GCPの Cloud Functions も同様のFaaS(Function as a Service)プラットフォームですが、単なるLambdaの代替品ではありません。GCPのイベント駆動アーキテクチャに最適化された独自の特徴があります。

この記事では、実際の開発・運用で重要となる以下の観点から両サービスを徹底比較します:

  • 実行環境とパフォーマンス特性
  • 料金体系とコスト最適化戦略
  • イベントソースと統合機能
  • 開発者体験と運用管理

基本スペック比較:実行環境の違いを理解する

サポート言語(ランタイム)比較

言語 AWS Lambda GCP Cloud Functions
Node.js v16, v18, v20 v16, v18, v20
Python 3.8, 3.9, 3.10, 3.11, 3.12 3.8, 3.9, 3.10, 3.11, 3.12
Java 8, 11, 17, 21 11, 17, 21
Go 1.x 1.19, 1.20, 1.21
C# (.NET) Core 3.1, 6, 8 Core 3.1, 6, 8
Ruby 2.7, 3.2 2.6, 2.7, 3.0, 3.1, 3.2
PHP ❌ 非対応 ✅ 7.4, 8.1, 8.2
PowerShell ✅ Core 6.0 ❌ 非対応

ポイント

  • GCP: PHPのネイティブサポートが大きな特徴
  • AWS: PowerShellサポートでWindows系ワークロードに対応
  • GCP: 最新ランタイムへの対応が早い傾向

リソース制限とパフォーマンス

項目 AWS Lambda GCP Cloud Functions
最大実行時間 15分 60分(1st gen: 9分、2nd gen: 60分)
メモリ容量 128MB〜10,240MB(1MB単位) 128MB〜8,192MB
一時ディスク 512MB〜10,240MB(/tmp) 2GB(2nd gen)
環境変数 4KB 32KB
同時実行数 アカウント全体で1,000(調整可能) 関数ごとに1,000
コールドスタート 100-1000ms 100-800ms

パフォーマンスの特徴

  • Cloud Functions 2nd gen: より長い実行時間が必要なバッチ処理に有利
  • Lambda: よりきめ細かいメモリ調整が可能
  • Cloud Functions: 環境変数の制限が緩く、設定の柔軟性が高い

料金体系比較:隠れたコストまで含めた詳細分析

基本料金体系

項目 AWS Lambda GCP Cloud Functions
無料枠(月間) 100万リクエスト
400,000GB-秒
200万リクエスト
400,000GB-秒
リクエスト料金 $0.20/100万リクエスト $0.40/100万リクエスト
実行時間料金 $0.0000166667/GB-秒 $0.0000025/GB-秒(1st gen)
$0.0000024/GB-秒(2nd gen)

具体的な料金計算例

シナリオ: 月間300万リクエスト、平均実行時間200ms、メモリ512MBの関数

AWS Lambda

リクエスト料金: (3,000,000 - 1,000,000) × $0.20/1,000,000 = $0.40
実行時間料金: 
- GB-秒 = 2,000,000 × 0.2s × 0.5GB = 200,000GB-秒
- 無料枠超過分: 200,000 - 400,000 = 0(無料枠内)
月額料金: $0.40

GCP Cloud Functions (1st gen)

リクエスト料金: (3,000,000 - 2,000,000) × $0.40/1,000,000 = $0.40
実行時間料金:
- GB-秒 = 1,000,000 × 0.2s × 0.5GB = 100,000GB-秒
- 無料枠超過分: 100,000 - 400,000 = 0(無料枠内)
月額料金: $0.40

追加料金要素

項目 AWS Lambda GCP Cloud Functions
ネットワーク料金 VPC使用時のENI料金 VPC使用時の追加料金なし
ログ出力 CloudWatch Logs料金 Cloud Logging料金
モニタリング CloudWatch料金 Cloud Monitoring料金

イベントソースと統合機能:エコシステムの違い

主要なイベントソース比較

カテゴリ AWS Lambda GCP Cloud Functions
HTTP/API API Gateway, ALB, Lambda URL HTTP トリガー, Cloud Run との統合
ストレージ S3 オブジェクト操作 Cloud Storage オブジェクト操作
データベース DynamoDB ストリーム Firestore トリガー
メッセージング SQS, SNS, EventBridge Pub/Sub
スケジューリング EventBridge (CloudWatch Events) Cloud Scheduler
認証 Cognito Firebase Authentication

イベント駆動アーキテクチャの実装例

AWS Lambda(S3 + DynamoDB)

import json
import boto3

def lambda_handler(event, context):
    # S3イベントから情報取得
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = event['Records'][0]['s3']['object']['key']
    
    # DynamoDBに記録
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('FileProcessingLog')
    
    table.put_item(
        Item={
            'file_key': key,
            'bucket': bucket,
            'processed_at': int(time.time())
        }
    )
    
    return {'statusCode': 200}

Cloud Functions(Cloud Storage + Firestore)

from google.cloud import firestore
import functions_framework

@functions_framework.cloud_event
def process_file(cloud_event):
    # Cloud Storageイベントから情報取得
    data = cloud_event.data
    bucket = data['bucket']
    name = data['name']
    
    # Firestoreに記録
    db = firestore.Client()
    doc_ref = db.collection('file_processing_log').document()
    doc_ref.set({
        'file_name': name,
        'bucket': bucket,
        'processed_at': firestore.SERVER_TIMESTAMP
    })

開発者体験:デプロイメントと管理の比較

デプロイメント方法

AWS Lambda の場合

# AWS SAM を使用
sam init --runtime python3.9
sam build
sam deploy --guided

# または Terraform
terraform init
terraform apply

Cloud Functions の場合

# gcloud CLI でシンプルデプロイ
gcloud functions deploy my-function \
  --runtime python39 \
  --trigger-http \
  --allow-unauthenticated \
  --source .

# または Cloud Build + YAML
gcloud builds submit --config cloudbuild.yaml

CI/CDパイプライン比較

GitHub Actions での AWS Lambda デプロイ

- name: Deploy to Lambda
  uses: aws-actions/configure-aws-credentials@v1
  with:
    aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
    aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
    aws-region: us-east-1

- name: Deploy SAM application
  run: |
    sam build
    sam deploy --no-confirm-changeset

GitHub Actions での Cloud Functions デプロイ

- name: Deploy to Cloud Functions
  uses: google-github-actions/auth@v1
  with:
    credentials_json: ${{ secrets.GCP_SA_KEY }}

- name: Deploy function
  run: |
    gcloud functions deploy my-function \
      --runtime python39 \
      --trigger-http

高度な機能比較:エンタープライズ対応

セキュリティ機能

項目 AWS Lambda GCP Cloud Functions
VPC統合 VPC Lambda(ENI使用) VPC コネクタ
暗号化 KMS による暗号化 Cloud KMS による暗号化
IAM統合 IAM ロールベース Cloud IAM ベース
秘匿情報管理 Secrets Manager, Parameter Store Secret Manager
ネットワークセキュリティ Security Group ファイアウォール ルール

モニタリングとログ

項目 AWS Lambda GCP Cloud Functions
メトリクス CloudWatch メトリクス Cloud Monitoring
ログ CloudWatch Logs Cloud Logging
分散トレーシング X-Ray Cloud Trace
アラート CloudWatch Alarms Cloud Monitoring Alerts
ダッシュボード CloudWatch Dashboard Cloud Monitoring Dashboard

実践ハンズオン:両サービスでのAPI実装

RESTful APIの実装例

AWS Lambda + API Gateway

import json

def lambda_handler(event, context):
    http_method = event['httpMethod']
    path = event['path']
    
    if http_method == 'GET' and path == '/users':
        return {
            'statusCode': 200,
            'headers': {
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*'
            },
            'body': json.dumps([
                {'id': 1, 'name': 'Alice'},
                {'id': 2, 'name': 'Bob'}
            ])
        }
    
    return {
        'statusCode': 404,
        'body': json.dumps({'error': 'Not Found'})
    }

Cloud Functions (2nd gen)

import functions_framework
from flask import Request

@functions_framework.http
def api_handler(request: Request):
    if request.method == 'GET' and request.path == '/users':
        return {
            'users': [
                {'id': 1, 'name': 'Alice'},
                {'id': 2, 'name': 'Bob'}
            ]
        }
    
    return {'error': 'Not Found'}, 404

パフォーマンス最適化のベストプラクティス

コールドスタート対策

AWS Lambda

import boto3

# グローバルスコープでクライアント初期化
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('MyTable')

def lambda_handler(event, context):
    # 既に初期化済みのクライアントを使用
    response = table.get_item(Key={'id': event['id']})
    return response['Item']

Cloud Functions

from google.cloud import firestore

# グローバルスコープでクライアント初期化
db = firestore.Client()

@functions_framework.http
def get_user(request):
    user_id = request.args.get('id')
    doc = db.collection('users').document(user_id).get()
    return doc.to_dict()

メモリ使用量の最適化

最適化手法 AWS Lambda GCP Cloud Functions
メモリ設定 パフォーマンステストで最適値を特定 同様にテストで最適化
依存関係 Lambdaレイヤーで共通ライブラリを分離 requirements.txtの最適化
実行時間 メモリ増加でCPU性能向上 同様の関係性

選択指針:どちらを選ぶべきか?

AWS Lambda を選ぶべきケース

  • 既存のAWSエコシステムとの統合が重要
  • 豊富な経験者やコミュニティサポートが必要
  • 詳細なモニタリングとトレーシングが必須
  • エンタープライズレベルのガバナンスが必要

GCP Cloud Functions を選ぶべきケース

  • コスト効率を最優先したい場合
  • PHP アプリケーションを移行したい場合
  • シンプルなデプロイメントを重視する場合
  • 長時間実行(最大60分)が必要な処理がある場合

技術負債と移行コストの考慮

要因 AWS Lambda GCP Cloud Functions
学習コスト 低(AWS経験者前提) 中程度
既存システム統合 高(AWS内なら容易) 低〜中(新規構築なら容易)
運用ツール移行 不要 必要(モニタリング等)
チームスキル 既存スキル活用 新規習得必要

まとめ:サーバーレスの未来を見据えた選択

評価項目 AWS Lambda GCP Cloud Functions
機能の豊富さ ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐
料金効率 ⭐⭐⭐ ⭐⭐⭐⭐⭐
開発者体験 ⭐⭐⭐⭐ ⭐⭐⭐⭐⭐
エコシステム ⭐⭐⭐⭐⭐ ⭐⭐⭐
運用管理 ⭐⭐⭐⭐ ⭐⭐⭐⭐

AWS Lambda は成熟したエコシステムと豊富な統合オプションが魅力で、エンタープライズレベルのアプリケーションに適しています。一方、Cloud Functions はシンプルさとコスト効率に優れ、迅速な開発とデプロイが可能です。

どちらも優れたFaaSプラットフォームですが、既存のインフラ構成、チームのスキルレベル、コスト要件を総合的に検討して選択することが重要です。

次回は、NoSQLデータベースの領域に進みます。AWS DynamoDBとGCP Firestoreの違いを詳しく比較し、サーバーレスアーキテクチャに最適なデータベース選択を学びます。

この記事が役に立った方は、ぜひ「いいね」や「ストック」をお願いします!


シリーズ記事一覧

  • [【1日目】はじめの一歩!AWSエンジニアがGCPで最初にやるべきこと]
  • [【2日目】GCPのIAMはAWSとどう違う?「プリンシパル」と「ロール」の理解]
  • [【3日目】VPCとVPCネットワーク:GCPのネットワーク設計思想を理解する]
  • [【4日目】S3とCloud Storage:オブジェクトストレージを徹底比較]
  • [【5日目】RDSとCloud SQL:マネージドデータベースの運用管理の違い]
  • [【6日目】EC2とCompute Engine:インスタンスの起動から課金モデルまで]
  • [【7日目】1週間のまとめ:AWSとGCP、それぞれの得意なことと設計思想]
  • [【8日目】EKSとGKE:Kubernetesのマネージドサービスを比較体験!]
  • [【9日目】Dockerイメージをどこに置く?ECRとArtifact Registryを徹底比較]
  • [【10日目】LambdaとCloud Functions:サーバーレス関数を徹底比較](この記事)
  • [【11日目】DynamoDBとFirestore:サーバーレスNoSQLデータベース比較]
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?