Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 67 ยท Projects

Project: A URL Shortener with Queues and Caching

Build a URL shortener in Laravel 13 with slug generation, a cached redirect route, click counting in queued jobs, scheduled cleanup and Pest tests.

A URL shortener is a perfect small system for learning performance-minded Laravel. Creating a short link is rare and can be slow. Following one is frequent and must be as fast as possible, because someone is waiting for a redirect. That imbalance pushes you toward good habits: a cache in front of the database, bookkeeping (click counts) moved into a queue, and a scheduled job that removes expired rows.

You will build the whole flow: slug generation, the redirect route, a cache, click counting with a queued job, scheduled cleanup, and tests.

Laravel cannot run on this site, so the Laravel code is read-only: copy it into a fresh app (SQLite is fine) to try it. The runnable examples are plain PHP stand-ins for the core logic: slug generation, a cache in front of SQLite, and a click queue. Each section says which is which.

Design first

sequenceDiagram
    participant B as Browser
    participant R as Redirect route
    participant C as Cache
    participant D as Database
    participant Q as Queue worker
    B->>R: GET /aZ3k9Qx
    R->>C: get link:aZ3k9Qx
    alt cache miss
        C-->>R: nothing
        R->>D: select link by slug
        D-->>R: link row
        R->>C: store for one hour
    else cache hit
        C-->>R: link data
    end
    R->>Q: dispatch RecordClick(linkId)
    R-->>B: 302 to the long URL
    Q->>D: increment clicks

The redirect answers from the cache when it can and never waits for the click counter: that work is queued.

Three decisions shape the project. First, the redirect uses status 302, not 301: browsers cache a 301 for a long time and would never ask your server again, so you could neither count clicks nor change or disable the link. Second, the click count is written by a queued job after the redirect has been sent. Third, the lookup goes through the cache so popular links do not hit the database at all.

The table and the model

Terminal
php artisan make:model Link --migration --factory
PHP
Schema::create('links', function (Blueprint $table) {
    $table->id();
    $table->string('slug', 16)->unique();
    $table->text('url');
    $table->unsignedBigInteger('clicks')->default(0);
    $table->timestamp('expires_at')->nullable();
    $table->timestamps();

    $table->index('expires_at');
});

The unique index on slug is the real guarantee that two links never share a slug; application code can only make collisions unlikely. The index on expires_at keeps the cleanup query fast.

PHP
class Link extends Model
{
    use HasFactory, Prunable;

    protected $fillable = ['slug', 'url', 'expires_at'];

    protected function casts(): array
    {
        return ['expires_at' => 'datetime'];
    }

    public function prunable(): Builder
    {
        return static::where('expires_at', '<', now()->subDays(30));
    }

    protected static function booted(): void
    {
        static::deleted(fn (Link $link) => Cache::forget("link:{$link->slug}"));
    }
}

Deleting a link also removes its cache entry, so a deleted link stops redirecting immediately instead of living on in the cache for up to an hour.

Generating slugs

There are two common strategies. You can encode the row's numeric ID in base 62 (digits plus lowercase and uppercase letters): short, unique by construction, but sequential and therefore guessable. Or you can generate a random string and retry on collision: not guessable, but needs the retry loop. Random is the usual choice for public links:

PHP
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Str;

class CreateLink
{
    public function handle(string $url, ?\DateTimeInterface $expiresAt = null): Link
    {
        for ($attempt = 0; $attempt < 5; $attempt++) {
            try {
                return Link::create([
                    'slug' => Str::random(7),
                    'url' => $url,
                    'expires_at' => $expiresAt,
                ]);
            } catch (UniqueConstraintViolationException) {
                // someone else got that slug in the meantime: try another
            }
        }

        throw new RuntimeException('Could not generate a unique slug.');
    }
}

Do not check "does this slug exist?" first and insert afterwards: between the check and the insert another request can take the slug. Insert and let the unique index decide. Seven characters of base 62 give about 3.5 trillion combinations, so collisions are rare, and the retry cap stops an endless loop if something is wrong.

Here are both strategies as plain PHP. The "random" source is a scripted list so the output never changes, which lets you see the collision retry happen:

PHP Slug strategies: base 62 and random with retry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The sequential approach shows its weakness too: 1, 2, 3 are all valid links, so anyone can walk through them. Mixing a secret offset or shuffled alphabet hides this a little, but random strings are simpler.

PHP
class LinkController extends Controller
{
    public function store(Request $request, CreateLink $createLink): JsonResponse
    {
        $data = $request->validate([
            'url' => ['required', 'url:http,https', 'max:2048'],
            'expires_in_days' => ['nullable', 'integer', 'between:1,365'],
        ]);

        $link = $createLink->handle(
            $data['url'],
            isset($data['expires_in_days']) ? now()->addDays((int) $data['expires_in_days']) : null,
        );

        return response()->json(['short_url' => url($link->slug)], 201);
    }
}

Only http and https are accepted: a shortener that redirects to javascript: or file: URLs is a security hole. Public shorteners are also popular with spammers, so in a real service you would add a rate limit, require an account, and maybe check destinations against a block list. Slugs that you hand out yourself never collide with your own routes, but a custom alias feature must reject names such as login or dashboard with Rule::notIn([...]).

The redirect route

Register this route last in routes/web.php, so every other route gets a chance first:

PHP
use App\Http\Controllers\RedirectController;

Route::get('/{slug}', RedirectController::class)
    ->where('slug', '[0-9A-Za-z]{4,16}')
    ->name('redirect');
PHP
class RedirectController extends Controller
{
    public function __invoke(string $slug): RedirectResponse
    {
        $link = Cache::remember(
            "link:{$slug}",
            now()->addHour(),
            fn () => Link::where('slug', $slug)->first(['id', 'url', 'expires_at'])?->only(['id', 'url', 'expires_at'])
        );

        abort_if($link === null || ($link['expires_at'] !== null && $link['expires_at']->isPast()), 404);

        RecordClick::dispatch($link['id']);

        return redirect()->away($link['url'], 302);
    }
}

Cache::remember() returns the cached value if there is one; otherwise it runs the closure, stores the result and returns it. The cache holds a small array, not the whole model. The expiry check runs on every request, from the cached data, so an expired link stops working on time even while its cache entry is still alive. One honest limitation: when the closure returns null (an unknown slug), nothing useful is cached, so a flood of random slugs reaches the database. A rate limit on this route is the usual remedy.

The database itself needs nothing more than the unique index on slug: a lookup by a unique key is the fastest query you can run.

Counting clicks without slowing the redirect

PHP
class RecordClick implements ShouldQueue
{
    use Queueable;

    public function __construct(public int $linkId)
    {
    }

    public function handle(): void
    {
        Link::whereKey($this->linkId)->increment('clicks');
    }
}

increment('clicks') runs update links set clicks = clicks + 1, one atomic statement, so two workers handling clicks for the same link at the same moment never lose a count. This is the same reason you should never do $link->clicks++; $link->save(); for counters: two requests would both read 10 and both write 11.

If a single link is extremely popular, one database write per click becomes the bottleneck. The next step is to count in the cache (Cache::increment("clicks:{$id}"), which is atomic on Redis) and let a scheduled job add the totals to the database once a minute. Start simple and measure first.

The next example puts the pieces together as one plain-PHP program: SQLite for the links table, an array standing in for the cache (with hit and miss counters), a queue of click jobs, and a worker that applies them. It is a stand-in for the structure, not Laravel itself.

PHP Redirect with cache, click queue and cleanup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Look at the numbers. Seven requests cost only four database reads (one per distinct slug; nope is a miss that finds nothing), and the three popular requests came from the cache. The expired link old is cached but still answered with a 404, and it counts no clicks. All clicks were recorded after the redirects, by the worker, with one statement per click. In the cleanup, only the link whose expiry is more than 30 days old disappears.

Scheduled cleanup

The Prunable trait on the model plus one scheduler line removes old rows automatically:

PHP
// routes/console.php
use Illuminate\Support\Facades\Schedule;

Schedule::command('model:prune')->daily();

model:prune calls prunable() on each model that uses the trait and deletes the matching rows, firing model events (so the deleted hook clears the cache entry). It needs the scheduler running in production, either a cron entry that calls schedule:run every minute or a long-running schedule:work. For millions of rows, MassPrunable deletes in bulk without loading the models, which is faster but skips model events.

Tests

PHP
use App\Jobs\RecordClick;
use App\Models\Link;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Queue;

uses(Illuminate\Foundation\Testing\RefreshDatabase::class);

it('redirects to the long url and queues a click', function () {
    Queue::fake();
    $link = Link::factory()->create(['slug' => 'docs', 'url' => 'https://example.com/documentation']);

    $this->get('/docs')->assertRedirect('https://example.com/documentation');

    Queue::assertPushed(RecordClick::class, fn (RecordClick $job) => $job->linkId === $link->id);
});

it('returns 404 for unknown and expired links', function () {
    Link::factory()->create(['slug' => 'gone', 'expires_at' => now()->subMinute()]);

    $this->get('/nope')->assertNotFound();
    $this->get('/gone')->assertNotFound();
});

it('serves repeated visits from the cache', function () {
    Queue::fake();
    Link::factory()->create(['slug' => 'docs']);

    $this->get('/docs');

    expect(Cache::has('link:docs'))->toBeTrue();
});

it('counts clicks atomically in the job', function () {
    $link = Link::factory()->create(['clicks' => 0]);

    (new RecordClick($link->id))->handle();
    (new RecordClick($link->id))->handle();

    expect($link->fresh()->clicks)->toBe(2);
});

it('rejects non-http urls', function () {
    $this->postJson('/links', ['url' => 'javascript:alert(1)'])
        ->assertUnprocessable()
        ->assertJsonValidationErrors(['url']);
});

Queue::fake() replaces the real queue, so the first test checks that the redirect dispatched the right job without running it; the job's own test then runs handle() directly. That split (one test for dispatching, one for the work) keeps tests fast and failures easy to locate. See faking and mocking for more on fakes.

Ideas to extend it

  • Per-user dashboards with a link list and click charts, using the Livewire patterns from the previous project.
  • Store each click (time, referrer, country) in a separate clicks table for analytics, written by the same job, and aggregate it nightly.
  • Custom aliases with reserved-word checks, and QR codes for each short link.
  • Move the cache and queue to Redis, and put a CDN or edge cache in front for the hottest links.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the redirect use status 302 instead of 301?

    A browser that has seen a 301 may skip your server next time. A 302 keeps every visit flowing through your app.
  2. 2. What is the safest way to guarantee that two links never share a slug?

    Check-then-insert has a race window. A unique index decides atomically, and the application simply retries on a violation.
  3. 3. Why is the click count increased with increment('clicks') in a job?

    Reading, adding one and saving in PHP loses counts when two requests overlap. The SQL expression is atomic, and the queue keeps it out of the response time.
  4. 4. What does Cache::remember('key', 3600, fn () => ...) do?

    remember() is a get-or-compute helper. It avoids repeating the expensive lookup while the entry is fresh.
  5. 5. How does the Prunable trait fit into a scheduled cleanup?

    You describe which rows are old in prunable(), and the scheduled model:prune command removes them.

Summary

  • A shortener is read-heavy: put a cache in front of the database and keep writes such as click counts off the request path.
  • Use 302 redirects so every visit reaches your server; accept only http and https destinations.
  • Generate random slugs, rely on a unique index and retry on a violation instead of checking first.
  • Count with an atomic increment() in a queued job; consider cache counters and periodic flushes for very hot links.
  • Remove expired data with Prunable and model:prune on the scheduler, and clear cache entries when links are deleted.
  • Test dispatching with Queue::fake() and test the job's work separately.

Next: Project: Subscriptions, Billing and an Admin Panel