Storing long and shortened url in relational table with ID integer, as primary key and auto-increment
CREATE TABLE URL_SHORTENER_TABLE(
  id (integer, auto-increment, primary key)
  long_url (string)
  shortened_url (string)
);

generate API (POST)

// generate API (POST)
@RequestMapping(value = "/generate", method = RequestMethod.POST)
public String generate(String longUrl){
  // validate input ..
  
  // generate shortened url for the given long url
  // the service will use base62 conversion to perform the url
  String shortenedUrl = urlShortenerService.generateShortenedUrl(longUrl);
  
  // persist the new record in database.
  boolean isCompleted = database.persist(shortenedUrl, longUrl);
  if(isCompleted) {
    return shortenedUrl;
  }
  // throw Persistence Exception
  return null; // For simplicity returning null string.
}
// redirect API (GET)
@RequestMapping(value = "/redirect/{shortenedUrl}", method = RequestMethod.GET)
public Response redirect(@PathVariable String shortenedUrl){
  try {
    // check if the input is valid
    checkValidShortenedUrl(shortenedUrl);
    
    // fetch the long url from the database or cache
    String longUrl = database.getLongUrl(shortenedUrl);
    
    // redirect to the long url.
    redirectionService.redirect(longUrl);
    
    // peform some more metric actions...
    ResponseEntity.ok().build;
  }
  catch(IllegalArgumentException exception){
    log.error("Shortened Url entered is invalid");
    ResponseEntity.badRequest().build();
  }
}
Redirection flow
4 thought on “All you need to know about designing URL Shortener”
  1. I’d like to thank you for the efforts you have put in writing this site.
    I really hope to view the same high-grade content by you
    later on as well. In fact, your creative writing
    abilities has encouraged me to get my own blog now 😉

  2. Its like you read my mind! You appear to know so much
    about this, like you wrote the book in it or something.
    I think that you could do with some pics to drive the message home a
    little bit, but other than that, this is fantastic blog.

    A great read. I’ll certainly be back.

  3. whoah this blog is great i like studying your posts. Stay up the good work!
    You recognize, a lot of persons are looking around for
    this information, you could help them greatly.

Leave a Reply

Your email address will not be published. Required fields are marked *