0
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?

PHPで高負荷な「おみくじ機能」を最適化した話(20万/日対応)

0
Last updated at Posted at 2026-04-22

はじめに

最近、ランダム抽選系の機能(いわゆる「恋愛おみくじ」)を実装する機会がありました。

最初はシンプルに「DBからランダムで1件取得」するだけだったのですが、
アクセスが増えるにつれてパフォーマンス問題が顕著になりました。

特に以下のような課題が発生しました:

今回は、その改善方法をまとめます。


問題点:ORDER BY RAND() は使うな

よくある実装:

SELECT * FROM omikuji ORDER BY RAND() LIMIT 1;

$min = 1;
$max = 10000;
$id = rand($min, $max);

SELECT * FROM omikuji WHERE id >= $id LIMIT 1;

メリット
超高速
インデックス効く
デメリット
欠番があると偏る

解決策②:IDキャッシュ(おすすめ)

さらに改善:

事前にIDリストをキャッシュ
そこからランダム抽選

$ids = file_get_contents('ids_cache.php');
$idList = explode(',', $ids);

$randomId = $idList[array_rand($idList)];


解決策
0
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
0
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?