Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
20220319[Laravel]想定外のN+1アラート
Search
kuma
March 14, 2022
Programming
200
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
20220319[Laravel]想定外のN+1アラート
kuma
March 14, 2022
More Decks by kuma
See All by kuma
エンジニアの輪スライド
kumainataku
0
290
20220730[PHP]デザインパターン色々学んでみた
kumainataku
0
150
20220227 可読性って大事
kumainataku
0
95
20211027_僕の転職活動の振り返り.pdf
kumainataku
0
120
オブジェクト指向(超基礎)
kumainataku
0
170
20210516 LT資料(PHP echo print)
kumainataku
0
61
20210425 LT会(基本情報技術者)
kumainataku
0
52
202104 読書LT会
kumainataku
0
220
Other Decks in Programming
See All in Programming
SREの越境 / SRE Collaboration
y0hgi
2
310
ソニーのクラウド共通基盤の変遷とAI時代の開発スタイルに合わせた進化 / The Journey of Sony’s Common Cloud Platform and Its Evolution for AI-Native Development
kenjiyoneyama
0
270
Compiling a real-world CLI tool to native with Static Hermes
tmikov2023
0
120
設計次第でAIコードの読む量は減らせる / designing-for-code-reading
minodriven
35
17k
コードで差別化できない時代の ソフトウェアエンジニアリング / Software Engineering in an Era Where Code Doesn’t Differentiate
kishida
2
180
Kotlinの15年とServer-Side Kotlin
n_takehata
1
150
Vue Fes Japan の “作る側”に関わってみて
naokihaba
0
160
Atomic Design, Enforced: Scaling Mobile Design Systems (next.app devCon / droidCon Berlin 2026)
steliosf
PRO
0
170
Starting & Sustaining Code-Based E2E Testing for Non-Coding QA Teams( #jasstniigata )
teyamagu
PRO
1
1k
半永久的に提供し続けられるプライベートクラウドを目指して ― 利用者の認知負荷を抑えるAPI抽象化とハードウェア世代交代の基盤設計
tomokon
0
500
作って学ぶSpring BootのAuto Configuration / JJUG Night Seminar 2026-10-19
rshindo
0
140
JIS keyboard support in Omarchy
lef237
0
110
Featured
See All Featured
Utilizing Notion as your number one productivity tool
mfonobong
4
620
Navigating the Design Leadership Dip - Product Design Week Design Leaders+ Conference 2024
apolaine
2
480
The untapped power of vector embeddings
frankvandijk
2
1.9k
The Psychology of Web Performance [Beyond Tellerrand 2023]
tammyeverts
49
3.6k
Self-Hosted WebAssembly Runtime for Runtime-Neutral Checkpoint/Restore in Edge–Cloud Continuum
chikuwait
0
890
Chrome DevTools: State of the Union 2024 - Debugging React & Beyond
addyosmani
10
1.4k
Docker and Python
trallard
47
4.2k
Navigating Algorithm Shifts & AI Overviews - #SMXNext
aleyda
1
1.7k
Design of three-dimensional binary manipulators for pick-and-place task avoiding obstacles (IECON2024)
konakalab
0
620
Beyond borders and beyond the search box: How to win the global "messy middle" with AI-driven SEO
davidcarrasco
3
280
Building a Scalable Design System with Sketch
lauravandoore
464
34k
Fight the Zombie Pattern Library - RWD Summit 2016
marcelosomers
234
18k
Transcript
[Laravel]想定外のN+1アラート 2022 / 3 / 19 クマ
自己紹介 • 実務入って半年 • PHP(Laravel)、JavaScript(Vue)を書いてます。 • 好き↓ • タガが外れたように満腹まで食べる •
ラーメン屋のハシゴ、二郎系マシマシ…etc • 甘いもの • ミスド食べ放題いったり、パンケーキ食らったり • スイパラ行くのが直近目標 P-01
目次 • 話すこと • 前提(こっから本題) • やりたいこと • 起きたこと •
原因 • やったこと(本題おわり) • おわりに P-01
話すこと P-01
話す事 LaravelにてN+1が発生していないように見えたのだが、アラート が出たときの対応方法 ↓こんなの ※Laravel経験がないとイメージつきにくい内容かもです。。。 P-01
前提 P-01
前提 バージョン • PHP 8.0.2 • Laravel 8.5.0 P-01
前提 テーブル構成 P-01 blockedプロパティをチェックしてBANす るか否かをチェックする想定
前提 リレーション ↓Userモデル P-01 UserとUserAttributeで1対1のリレーションを構築
やりたいこと P-01
やりたいこと いわゆる「垢BAN機能」を実装したい 特定ユーザーをログインできなくする、アレです。 ※ちなみに、この機能自体は本題と関係ないです。 P-01
やりたいこと <?php namespace App¥Http¥Middleware; use Closure; use Illuminate¥Http¥Request; use Illuminate¥Support¥Facades¥Auth;
class CheckBlockedUser { public function handle(Request $request, Closure $next) { if (Auth::check() && $user = Auth::user()) { $userAttribute = $user->userAttribute; // ※ if ($userAttribute && $userAttribute->blocked == 1) { Auth::logout(); $request->session()->regenerateToken(); Log::notice('Block user from login status. '.$user->id); return redirect()->route('login') ->withErrors(['error' => 'アカウントは凍結されています。']); } } return $next($request); } } P-01 App/Middleware/CheckBlockedUser userAttributeを取得 ➡ここでクエリが発行 (SELECT * FROM user_attribute …) ※補足 ここでblockedプロパティをチェックして BANするか否かをチェック
起きたこと P-01
起きたこと • ブロックユーザーで動作テスト ➡垢BAN機能は実装done(よしよし。) • 正常ユーザー(非ブロックユーザー)での動作テスト ➡ログインできるが、以下アラート発生(おん!?) P-01
起きたこと • このアラートはN+1を勝手に検出して教えてくれるライブラリ 「laravel-query-detector」によるもの • 要約:「User経由でUserAttributeを取得するクエリが必要以 上に実行されているからEager Loadingしてね!」 P-01
やりたいこと class CheckBlockedUser { public function handle(Request $request, Closure $next)
{ if (Auth::check() && $user = Auth::user()) { $userAttribute = $user->userAttribute; // ※ if ($userAttribute && $userAttribute->blocked == 1) { Auth::logout(); $request->session()->regenerateToken(); Log::notice('Block user from login status. '.$user->id); return redirect()->route('login') ->withErrors(['error' => 'アカウントは凍結されています。']); } } return $next($request); } } P-01 App/Middleware/CheckBlockedUser(再掲) ここでしかクエリ発行していないんですが、、、 ただ、、、 ➡原因調査
原因 P-01
原因 P-01 おなじみのLaravel-debugbarで確認したところすぐに判明
原因 P-01 原因はMiddlewareと別でControllerでも同じようなuserAttribute の取得(クエリの実行)をしていた $user = User::find(Auth::id()); // ココでuserAttributeを取得するSQLが発行 $userAttribute
= $user->userAttribute; App/Controller/TestController(実際のコード)
原因 P-01 Laravelとしては 「Middlewareで$userAttributeを取得するよ」 「あれ、Controllerでも取得しているね。だったらN+1だね」 と判断しちゃうんだな。。。 ↓アラート発生時のクエリ(イメージ) SELECT * FROM
use_attribute; … … SELECT * FROM use_attribute; // 2回同じクエリが発行
やったこと P-01
やったこと 案は2つ。 1, Middlewareで取得した$userAttributeをControllerまで渡す? ➡現実的ではない。 2, アラートを表示させない ➡これで行く P-01
やったこと 特定条件下でN+1を検出してもアラートを表示させないようにする ➡具体的にはlaravel-query-detector をインストールした時に入っ てくるconfig/querydetector.phpのexceptの箇所に以下記述 ➡無事アラートは発生しなくなった! P-01 'except' => [
User::class => [ UserAttribute::class, 'userAttribute', ], ] App/Controller/TestController(追加したコード) 今回はUser➡userAttributeの際にN+1が発生し たので、このように記述
おわりに P-01
おわりに • 自分はdevelopとの差分だけ見て「N+1起こるわけな い!」と決めつけた結果痛い目にあった。。。 • どんなことでも共通するのは「自分の修正した差分だ けに問題が潜んでいるとは限らない」ということ →ある程度問題に取り組んで解決しなければ、視野を広 げる(抽象度を上げる)ことの重要性を痛感 P-01
ご清聴ありがとうございました。 P-01