SlideShare uma empresa Scribd logo
1 de 28
Baixar para ler offline
今更ながらDBのカウントアップ
の話
2018/11/22 - ARCANA Meetup #44
カツミ ユキヒロ
⾃⼰紹介
所属:スタジオ・アルカナ
名前:勝⾒ 幸弘
年齢:32歳
サーバサイドメイン
注意事項
• ソースは動かして確認はしているが、バージョ
ンが古かったり雑なコードが含まれます。マ
ネしないで下さい。
例えば動画のイイネを
カウントする処理
こんなイメージ
ユーザ1 ユーザ2動画1
こんなイメージ
ユーザ1 ユーザ2動画1
イイネ
こんなイメージ
ユーザ1 ユーザ2動画1
イイネ
イイネ数=1
こんなイメージ
ユーザ1 ユーザ2動画1
イイネ イイネ
イイネ数=1
こんなイメージ
ユーザ1 ユーザ2動画1
イイネ イイネ
イイネ数=2
前提条件
• 1ユーザにつきイイネは1回のみ。
テーブル作成
(laravelのmigrate)
public function up()
{
Schema::create('movies', function (Blueprint $table) {
$table->increments('id');
$table->integer('vote')->default(0);
});
Schema::create('users_votes', function (Blueprint $table) {
$table->unsignedInteger('movie_id');
$table->unsignedInteger('user_id');
});
}
public function down()
{
Schema::dropIfExists('movies');
Schema::dropIfExists('users_votes');
}
users_votesテーブルにデータがなければ初回イイネ
カウント処理
(laravelのroutes/web.php)
use Illuminate¥DatabaseEloquentModel;
class UsersVotes extends Model {
class Movie extends Model {
protected $guarded = [];
public $timestamps = false;
}
class UsersVotes extends Model {
protected $guarded = [];
public $timestamps = false;
}
Route::get('/v1/movie/{id}/{user_id}', function ($id, $user_id) {
DB::beginTransaction();
$users_vote = UsersVotes::firstOrCreate(['movie_id' => $id, 'user_id' => $user_id]);
if ($users_vote->wasRecentlyCreated) {
Movie::firstOrCreate(['id' => $id])->increment('vote');
DB::commit();
return '初回いいね';
}
DB::commit();
return '既にいいね';
});
users_votesテーブルにインサートできた時だけカウントアップ
/v1/movie/1/1
と
/v1/movie/1/2
にアクセスする
実⾏されたsql
[06:55:50] select * from `users_votes` where (`movie_id` = 1 and `user_id` = 1) limit 1
[06:55:50] insert into `users_votes` (`movie_id`, `user_id`) values (1, 1)
[06:55:50] select * from `movies` where (`id` = 1) limit 1
[06:55:50] insert into `movies` (`id`) values (1)
[06:55:50] update `movies` set `vote` = `vote` + 1 where `id` = 1
[06:56:31] select * from `users_votes` where (`movie_id` = 1 and `user_id` = 2) limit 1
[06:56:31] insert into `users_votes` (`movie_id`, `user_id`) values (1, 2)
[06:56:31] select * from `movies` where (`id` = 1) limit 1
[06:56:31] update `movies` set `vote` = `vote` + 1 where `id` = 1
ユーザ1のアクセス
ユーザ2のアクセス
実⾏されたsql
ユーザ1のアクセス
ユーザ2のアクセス
両⽅とも初回アクセスのためusers_votesにはinsertされる
[06:55:50] select * from `users_votes` where (`movie_id` = 1 and `user_id` = 1) limit 1
[06:55:50] insert into `users_votes` (`movie_id`, `user_id`) values (1, 1)
[06:55:50] select * from `movies` where (`id` = 1) limit 1
[06:55:50] insert into `movies` (`id`) values (1)
[06:55:50] update `movies` set `vote` = `vote` + 1 where `id` = 1
[06:56:31] select * from `users_votes` where (`movie_id` = 1 and `user_id` = 2) limit 1
[06:56:31] insert into `users_votes` (`movie_id`, `user_id`) values (1, 2)
[06:56:31] select * from `movies` where (`id` = 1) limit 1
[06:56:31] update `movies` set `vote` = `vote` + 1 where `id` = 1
実⾏されたsql
ユーザ1のアクセス
ユーザ2のアクセス
動画への初回アクセスであるユーザ1の場合のみmoviesにinsertされる
[06:55:50] select * from `users_votes` where (`movie_id` = 1 and `user_id` = 1) limit 1
[06:55:50] insert into `users_votes` (`movie_id`, `user_id`) values (1, 1)
[06:55:50] select * from `movies` where (`id` = 1) limit 1
[06:55:50] insert into `movies` (`id`) values (1)
[06:55:50] update `movies` set `vote` = `vote` + 1 where `id` = 1
[06:56:31] select * from `users_votes` where (`movie_id` = 1 and `user_id` = 2) limit 1
[06:56:31] insert into `users_votes` (`movie_id`, `user_id`) values (1, 2)
[06:56:31] select * from `movies` where (`id` = 1) limit 1
[06:56:31] update `movies` set `vote` = `vote` + 1 where `id` = 1
実⾏されたsql
ユーザ1のアクセス
ユーザ2のアクセス
動画1のイイネカウントアップが流れる
[06:55:50] select * from `users_votes` where (`movie_id` = 1 and `user_id` = 1) limit 1
[06:55:50] insert into `users_votes` (`movie_id`, `user_id`) values (1, 1)
[06:55:50] select * from `movies` where (`id` = 1) limit 1
[06:55:50] insert into `movies` (`id`) values (1)
[06:55:50] update `movies` set `vote` = `vote` + 1 where `id` = 1
[06:56:31] select * from `users_votes` where (`movie_id` = 1 and `user_id` = 2) limit 1
[06:56:31] insert into `users_votes` (`movie_id`, `user_id`) values (1, 2)
[06:56:31] select * from `movies` where (`id` = 1) limit 1
[06:56:31] update `movies` set `vote` = `vote` + 1 where `id` = 1
実は問題があります
ユーザ1とユーザ2が同時に
動画1にアクセスした場合
ユーザ1とユーザ2が同時に動画
1にアクセスした場合
[09:25:30] select * from `users_votes` where (`movie_id` = 1 and `user_id` = 2) limit 1
[09:25:30] select * from `users_votes` where (`movie_id` = 1 and `user_id` = 1) limit 1
[09:25:30] insert into `users_votes` (`movie_id`, `user_id`) values (1, 2)
[09:25:30] insert into `users_votes` (`movie_id`, `user_id`) values (1, 1)
[09:25:30] select * from `movies` where (`id` = 1) limit 1
[09:25:30] select * from `movies` where (`id` = 1) limit 1
[09:25:30] insert into `movies` (`id`) values (1)
[09:25:30] update `movies` set `vote` = `vote` + 1 where `id` = 1
[09:25:30] SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1'
for key 'PRIMARY' (SQL: insert into `movies` (`id`) values (1))
moviesがinsertされる初回のみエラーが発⽣する
何らかの理由により
ユーザ1が動画1に
同時に2回アクセスした場合
何らかの理由によりユーザが動画1
に同時に2回アクセスした場合のsql
[1回⽬] select * from `users_votes` where (`movie_id` = 1 and `user_id` = 1) limit 1
[2回⽬] select * from `users_votes` where (`movie_id` = 1 and `user_id` = 1) limit 1
[1回⽬] insert into `users_votes` (`movie_id`, `user_id`) values (1, 1)
[2回⽬] insert into `users_votes` (`movie_id`, `user_id`) values (1, 1)
[1回⽬] select * from `movies` where (`id` = 1) limit 1
[2回⽬] select * from `movies` where (`id` = 1) limit 1
[1回⽬] insert into `movies` (`id`) values (1)
[2回⽬] insert into `movies` (`id`) values (1)
[1回⽬] update `movies` set `vote` = `vote` + 1 where `id` = 1
[1回⽬] update `movies` set `vote` = `vote` + 1 where `id` = 1
[1回⽬] select * from `users_votes` where (`movie_id` = 1 and `user_id` = 1) limit 1
[2回⽬] select * from `users_votes` where (`movie_id` = 1 and `user_id` = 1) limit 1
[1回⽬] insert into `users_votes` (`movie_id`, `user_id`) values (1, 1)
[2回⽬] insert into `users_votes` (`movie_id`, `user_id`) values (1, 1)
[1回⽬] select * from `movies` where (`id` = 1) limit 1
[2回⽬] select * from `movies` where (`id` = 1) limit 1
[1回⽬] insert into `movies` (`id`) values (1)
[2回⽬] insert into `movies` (`id`) values (1)
[1回⽬] update `movies` set `vote` = `vote` + 1 where `id` = 1
[2回⽬] update `movies` set `vote` = `vote` + 1 where `id` = 1
insertが2回実⾏されてしまう
何らかの理由によりユーザが動画1
に同時に2回アクセスした場合のsql
サーバサイドだけで対応する
にはどうするか?
の1例。
テーブル作成
(laravelのmigrate)
public function up()
{
Schema::create('v2_movies', function (Blueprint $table) {
$table->increments('id');
$table->integer('vote')->default(0);
});
Schema::create('v2_users_votes', function (Blueprint $table) {
$table->unsignedInteger('movie_id');
$table->unsignedInteger('user_id');
$table->tinyInteger('is_update')->default(0);
$table->unique(['movie_id', 'user_id']);
});
}
public function down()
{
Schema::dropIfExists('v2_movies');
Schema::dropIfExists('v2_users_votes');
}
ユニークキーを張る
カウント処理
(laravelのroutes/web.php)
class V2UsersVotes extends Model {
protected $guarded = [];
public $timestamps = false;
}
class V2Movies2 extends Model {
protected $guarded = [];
public $timestamps = false;
}
Route::get('/v2/movie/{id}/{user_id}', function ($id, $user_id) {
DB::beginTransaction();
DB::statement("INSERT INTO `v2_users_votes` (`movie_id`, `user_id`) VALUES ($id, $user_id) ON DUPLICATE KEY UPDATE `is_update` = 1");
$users_vote = V2UsersVotes::where('movie_id', $id)->where('user_id', $user_id)->first();
if ($users_vote->is_update === 0) {
// update の場合でも id = 1にロックがかかる。
DB::statement("INSERT INTO `v2_movies` (`id`, `vote`) VALUES ($id, 1) ON DUPLICATE KEY UPDATE `vote` = `vote` + 1");
DB::commit();
return '初回いいね';
}
return '既にいいね';
});
sqlをこうして
カウント処理
(laravelのroutes/web.php)
class V2UsersVotes extends Model {
protected $guarded = [];
public $timestamps = false;
}
class V2Movies2 extends Model {
protected $guarded = [];
public $timestamps = false;
}
Route::get('/v2/movie/{id}/{user_id}', function ($id, $user_id) {
DB::beginTransaction();
DB::statement("INSERT INTO `v2_users_votes` (`movie_id`, `user_id`) VALUES ($id, $user_id) ON DUPLICATE KEY UPDATE `is_update` = 1");
$users_vote = V2UsersVotes::where('movie_id', $id)->where('user_id', $user_id)->first();
if ($users_vote->is_update === 0) {
// update の場合でも id = 1にロックがかかる。
DB::statement("INSERT INTO `v2_movies` (`id`, `vote`) VALUES ($id, 1) ON DUPLICATE KEY UPDATE `vote` = `vote` + 1");
DB::commit();
return '初回いいね';
}
return '既にいいね';
});
sqlをこうする
スライドを作成する
時間がないので残りは
実演しつつ解説

Mais conteúdo relacionado

Destaque

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Destaque (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

今更ながらDBのカウントアップの話