Thursday, March 16, 2017

Laravel model accessor fetching from cache - performance enhancements

I have a list of items in database and each item has option to be voted down or up. Those votes are stored in MySql along with other item fields. For example someting like this:

Schema::create('items', function ($table) {
    $table->increments('id');
    $table->text('message');
    $table->integer('up_votes')->unsigned()->default(0);
    $table->integer('down_votes')->unsigned()->default(0);
    $table->timestamps();
});

User can vote down/up every day. When user decides to vote I store his decision to memcached for one day and increase one of the fields (up_votes or down_votes) accordingly.

$voteKey = sprintf('%s-%s', $request->ip(), $item->id);

if (!Cache::has($voteKey)) {
    $vote = $request->get('vote');

    $this->item->increment($vote ? 'up_votes' : 'down_votes');
    Cache::put($voteKey, $vote, (60*24));
}

Next I want to have information about how certain user voted. I created accessor in model:

public function getVoteAttribute($value)
{
    $voteKey = sprintf('%s-%s', Request::ip(), $this->id);

    return $this->attributes['vote'] = Cache::get($voteKey);
}

protected $appends = ['vote'];

Is this smart to do or could there be some performance issues with long lists? If 100 items are returned, there are 100 connections to memcached per user. How can I improve this or is this something I should not much worry about because cache server can handle this amount of connections with no problem.



via izupet

Advertisement