LoginSignup
12
7

More than 5 years have passed since last update.

Lambdaでグローバルに置いた変数は使いまわされる

Last updated at Posted at 2018-03-02

Lambdaに置いたコードって、呼び出されるたびにコードを読み込んで実行されると思っていましたが違うようです。
とある外部モジュールを使っていたのですが、シングルトンとして初期化してexportされているオブジェクトの動きが妙だったので試してみました。

singleton.js
function Singleton() {
    this.counter = 0;
}
// シングルトンとして初期化してexport
module.exports = new Singleton();
index.js
// Singletonオブジェクトを取得
const singleton = require('./singleton');

exports.handler = (event, context, callback) => {
    // カウンターをインクリメント
    singleton.counter++;
    // カウンター値を返す
    callback(null, singleton.counter);
};

このLambdaを何度も呼び出してみます。

結果
(1回目) 1
(2回目) 2
(3回目) 3

外部から読み込もうが内部に書こうが、結果は同じです。もっとシンプルに書くとこう。

index.js
const singleton = {
    counter : 0    
};

exports.handler = (event, context, callback) => {
    // カウンターをインクリメント
    singleton.counter++;
    // カウンター値を返す
    callback(null, singleton.counter);
};
結果
(1回目) 1
(2回目) 2
(3回目) 3

えっ、もしかして常識…?

(追記)
一定時間呼び出されないとリセットされるようなので、使いまわされても使いまわされなくても動くように作る必要があります。
また、デプロイしなおすと必ずリセットされます。

12
7
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
12
7