Crawler
Crawler
What is tinyurl?
tinyurl is a URL service that users enter a long URL and then the service return a shorter
and unique url such as "http://tiny.me/5ie0V2". The highlight part can be any string with 6 letters
containing [0-9, a-z, A-Z]. That is, 62^6 ~= 56.8 billions unique strings.
How it works?
On Single Machine
Suppose we have a database which contains three columns: id (auto increment), actual url, and
shorten url.
Intuitively, we can design a hash function that maps the actual url to shorten url. But string to string
mapping is not easy to compute.
Notice that in the database, each record has a unique id associated with it. What if we convert the id
to a shorten url?
Basically, we need a Bijective function f(x) = y such that
On Multiple Machine
Suppose the service gets more and more traffic and thus we need to distributed data onto multiple
servers.
We can use Distributed Database. But maintenance for such a db would be much more complicated
(replicate data across servers, sync among servers to get a unique id, etc.).
Alternatively, we can use Distributed Key-Value Datastore.
Some distributed datastore (e.g. Amazon's Dynamo) uses Consistent Hashing to hash servers and
inputs into integers and locate the corresponding server using the hash value of the input. We can
apply base conversion algorithm on the hash value of the input.
1. Convert the shorten url back to the key using base conversion (from 62-base to 10-base);
2. Locate the server containing that key and return the longUrl.
---------
Further Readings
Ask Question
up I want to create a URL shortener service where you can write a long URL into an input
vote473do field and the service shortens the URL to "http://www.example.org/abcdef".
wn vote
Edit: Due to the ongoing interest in this topic, I've published an efficient solution to
GitHub, with implementations for JavaScript, PHP, Python and Java. Add your
favorite
algorithm url
shareimprove this question edited Sep 27 '16 at 14:56 asked Apr 12 '09 at 16:29
caw
8,79646126238
3 @gudge The point of those functions is that they have an inverse function. This means you can have
both encode() and decode() functions. The steps are, therefore: (1) Save URL in database (2) Get unique row
for that URL from database (3) Convert integer ID to short string with encode(), e.g. 273984 to
short string (e.g. f4a4) in your sharable URLs (5) When receiving a request for a short string (e.g.
string to an integer ID with decode() (6) Look up URL in database for given ID. For conversion,
use: github.com/delight-im/ShortURL – caw Feb 10 '15 at 10:31
@Marco, what's the point of storing the hash in the database? – Maksim Vi. Jul 11 '15 at 9:04
2 @MaksimVi. If you have an invertible function, there's none. If you had a one-way hash function, there would be
one. – caw Jul 14 '15 at 14:47
would it be wrong if we used simple CRC32 algorithm to shorten a URL? Although very unlikely of a collision (a CRC
output is usually 8 characters long and that gives us over 30 million possibilities) If a generated CRC32 output was
already used previously and was found in the database, we could salt the long URL with a random number until we
find a CRC32 output which is unique in my database. How bad or different or ugly would this be for a simple
solution? – Syed Rakib Al Hasan Mar 22 '16 at 9:41
Typical number to short string conversion approach in Java – Aniket Thakur May 14 '16 at 9:41
add a comment
22 Answers
activeoldest votes
up I would continue your "convert number to string" approach. However you will realize
vote608do that your proposed algorithm fails if your ID is a prime and greater than 52.
wn vote accepted
Theoretical background
You need a Bijective Function f. This is necessary so that you can find a inverse
function g('abc') = 123 for your f(123) = 'abc' function. This means:
There must be no x1, x2 (with x1 ≠ x2) that will make f(x1) = f(x2),
and for every y you must be able to find an x so that f(x) = y.
How to convert the ID to a shortened URL
digits = []
digits = digits.reverse
Now map the indices 2 and 1 to your alphabet. This is how your mapping (with an
array for example) could look like:
0 → a
1 → b
...
25 → z
...
52 → 0
61 → 9
With 2 → c and 1 → b you will receive cb62 as the shortened URL.
http://shor.ty/cb
How to resolve a shortened URL to the initial ID
The reverse is even easier. You just do a reverse lookup in your alphabet.
Ruby
Python
CoffeeScript
Haskell
Perl
C#
shareimprove this answer edited Dec 10 '14 at 4:18 community wiki
12 Don't forget to sanitize the URLs for malicious javascript code! Remember that javascript can be base64 encoded
a URL so just searching for 'javascript' isn't good enough.j – Bjorn Tipling Apr 14 '09 at 8:05
2 A function must be bijective (injective and surjective) to have an inverse. – Gumbo May 4 '10 at 20:28
30 Food for thought, it might be useful to add a two character checksum to the url. That would prevent direct iteratio
of all the urls in your system. Something simple like f(checksum(id) % (62^2)) + f(id) = url_id – koblas
13:53
6 As far as sanitizing the urls go, one of the problems you're going to face is spammers using your service to mask
their URLS to avoid spam filters. You need to either limit the service to known good actors, or apply spam filtering
the long urls. Otherwise you WILL be abused by spammers. – Edward Falk May 26 '13 at 15:34
43 Base62 may be a bad choice because it has the potential to generate f* words (for
example, 3792586=='F_ck' with u in the place of _). I would exclude some characters like u/U in order to
minimize this. – Paulo Scardine Jun 28 '13 at 16:02
shareimprove this answer edited May 4 '10 at 20:25 answered Apr 12 '09 at 16:34
shoosh
42k38159269
4 asides from the fact that A-Z, a-z and 0-9 = 62 chars, not 40, you are right on the mark. – Evan Teran
16:39
Thanks! Should I use the base-62 alphabet then? en.wikipedia.org/wiki/Base_62 But how can I convert the ids to a
base-62 number? – caw Apr 12 '09 at 16:46
Thank you! That's really simple. :) Do I have to do this until the dividend is 0? Will the dividend always be 0 at some
point? – caw Apr 12 '09 at 17:04
2 with enough resources and time you can "browse" all the URLs of of any URL shortening service. –
at 21:10
2701421 1,7051126
I really like the idea, the only problem i have with it is that i keep getting the num variable in the decode function out
of bounds(even for long), do you have any idea how to make it work? or is it theoretical only? – user1322801
'16 at 19:07
@user1322801: Presumably you're trying to decode something that was far larger than what the encode function ca
actually handle. You could get some more mileage out of it if you converted all of the "ints" to BigInteger, but unless
you've got > 9223372036854775807 indexes, long should probably be enough. – biggusjimmus Jul 19 '16 at 6:08
How about add custom URL shortener? – Yosua Lijanto Binar Aug 31 '16 at 14:13
add a comment
up Not an answer to your question, but I wouldn't use case-sensitive shortened URLs. They
vote27do are hard to remember, usually unreadable (many fonts render 1 and l, 0 and O and other
wn vote
characters very very similar that they are near impossible to tell the difference) and
downright error prone. Try to use lower or upper case only.
Also, try to have a format where you mix the numbers and characters in a predefined
form. There are studies that show that people tend to remember one form better than
others (think phone numbers, where the numbers are grouped in a specific form). Try
something like num-char-char-num-char-char. I know this will lower the combinations,
especially if you don't have upper and lower case, but it would be more usable and
therefore useful.
Ash
531166
1 Thank you, very good idea. I haven't thought about that yet. It's clear that it depends on the kind of use whether
that makes sense or not. – caw Apr 12 '09 at 18:22
14 It won't be an issue if people are strictly copy-and-pasting the short urls. – Edward Falk May 26 '13 at 15:35
1 The purpose of short url's is not to be memorable or easy to speak. Is only click or copy/paste. – hugomn
14:12
add a comment
up My approach: Take the Database ID, then Base36 Encode it. I would NOT use both
vote22do Upper AND Lowercase letters, because that makes transmitting those URLs over the
wn vote
telephone a nightmare, but you could of course easily extend the function to be a base 62
en/decoder.
shareimprove this answer answered Apr 14 '09 at 8:02
Michael Stum♦
101k91335487
Thanks, you're right. Whether you have 2,176,782,336 possibilities or 56,800,235,584, it's the same: Both will be
enough. So I will use base 36 encoding. – caw Apr 14 '09 at 18:22
It may be obvious but here is some PHP code referenced in wikipedia to do base64 encode in
php tonymarston.net/php-mysql/converter.html – Ryan White Jul 13 '10 at 15:33
add a comment
$result = '';
$base = count($this->dictionary);
$result = array_reverse($result);
return join("", $result);
}
$input = str_split($input);
foreach($input as $char)
{
$pos = array_search($char, $this->dictionary);
$i = $i * $base + $pos;
}
return $i;
}
}
shareimprove this answer answered Nov 4 '11 at 20:10
Xeoncross
22.7k49184281
add a comment
up You could hash the entire URL, but if you just want to shorten the id, do as marcel
vote3do suggested. I wrote this python implementation:
wn vote
https://gist.github.com/778542
shareimprove this answer answered Jan 17 '11 at 21:35
bhelx
673
add a comment
up C# version:
public class UrlShortener
vote3do
{
wn vote private static String ALPHABET =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private static int BASE = 62;
return num;
}
}
shareimprove this answer edited Aug 2 '14 at 12:30 answered Mar 8 '13 at 20:17
user1477388
10.3k1573154
add a comment
19.9k44489
"Sorry, it looks like spammers got to this. Try tinyurl instead." – takeshin Jan 31 '10 at 17:24
to the demo site. The source code is still downloadable from Sourceforge. – Alister Bulman Feb 12 '10 at 22:02
add a comment
else:
pval = pow(62,p)
nval = i/pval
remainder = i % pval
if nval <= 61:
return lookup(nval) + incode(i % pval)
else:
return incode(i, p+1)
return incode()
shareimprove this answer edited Nov 21 '09 at 22:51 answered Nov 21 '09 at 22:21
MrChrisRodriguez
12315
add a comment
up Why not just translate your id to a string? You just need a function that maps a digit
vote1do between, say, 0 and 61 to a single letter (upper/lower case) or digit. Then apply this to
wn vote
create, say, 4-letter codes, and you've got 14.7 million URLs covered.
cr333
605713
add a comment
up // simple approach
vote1do $original_id = 56789;
wn vote
$shortened_id = base_convert($original_id, 10, 36);
phirschybar
3,84273553
This is probably correct but you can't chose your alphabet. – caw Dec 20 '11 at 17:51
add a comment
Simon East
22.2k88381
add a comment
up Don't know if anyone will find this useful - it is more of a 'hack n slash' method, yet is
vote1do simple and works nicely if you want only specific chars.
wn vote
$dictionary = "abcdfghjklmnpqrstvwxyz23456789";
$dictionary = str_split($dictionary);
// Encode
$str_id = '';
$base = count($dictionary);
while($id > 0) {
$rem = $id % $base;
$id = ($id - $rem) / $base;
$str_id .= $dictionary[$rem];
}
// Decode
$id_ar = str_split($str_id);
$id = 0;
for($i = count($id_ar); $i > 0; $i--) {
$id += array_search($id_ar[$i-1], $dictionary) * pow($base, $i -
1);
}
shareimprove this answer edited Mar 29 '12 at 22:00 answered Mar 29 '12 at 21:42
Ryan Charmley
815814
add a comment
result = ''
while id_number > 0:
id_number, mod = divmod(id_number, alphabet_len)
result = alphabet[mod] + result
return result
Davmuz
610611
add a comment
up For a similar project, to get a new key, I make a wrapper function around a random string
vote0do generator that calls the generator until I get a string that hasn't already been used in my
wn vote
hashtable. This method will slow down once your name space starts to get full, but as you
have said, even with only 6 characters, you have plenty of namespace to work with.
shareimprove this answer answered Apr 22 '11 at 18:04
Joel Berger
16.9k43785
Has this approach worked out for you in the long run? – Chris May 10 '16 at 13:40
To be honest, I have no idea to which project I was referring there :-P – Joel Berger May 10 '16 at 16:34
add a comment
/**
* A nice shorting class based on Ryan Charmley's suggestion see
the link on stackoverflow below.
* @author Svetoslav Marinov (Slavi) | http://WebWeb.ca
* @see http://stackoverflow.com/questions/742013/how-to-code-a-
url-shortener/10386945#10386945
*/
class App_Shorty {
/**
* Explicitely omitted: i, o, 1, 0 because they are
confusing. Also use only lowercase ... as
* dictating this over the phone might be tough.
* @var string
*/
private $dictionary = "abcdfghjklmnpqrstvwxyz23456789";
private $dictionary_array = array();
/**
* Gets ID and converts it into a string.
* @param int $id
*/
public function encode($id) {
$str_id = '';
$base = count($this->dictionary_array);
return $str_id;
}
/**
* Converts /abc into an integer ID
* @param string
* @return int $id
*/
public function decode($str_id) {
$id = 0;
$id_ar = str_split($str_id);
$base = count($this->dictionary_array);
return $id;
}
}
?>
shareimprove this answer edited Apr 30 '12 at 16:42 answered Apr 30 '12 at 16:17
Svetoslav Marinov
79078
Yes. Did you see the comment just below the class declaration ? – Svetoslav Marinov Nov 5 '15 at 10:08
add a comment
up I have a variant of the problem, in that I store web pages from many different authors and
vote0do need to prevent discovery of pages by guesswork. So my short URLs add a couple of
wn vote
extra digits to the Base-62 string for the page number. These extra digits are generated
from information in the page record itself and they ensure that only 1 in 3844 URLs are
valid (assuming 2-digit Base-62). You can see an outline description
at http://mgscan.com/MBWL.
shareimprove this answer answered Mar 15 '15 at 9:42
Graham
6127
add a comment
const alphabet =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
/* Special case */
if n == 0 {
return string(alphabet[0])
}
/* Map */
for n > 0 {
r := n % uint64(len(alphabet))
t = append(t, alphabet[r])
n = n / uint64(len(alphabet))
}
/* Reverse */
for i, j := 0, len(t) - 1; i < j; i, j = i + 1, j - 1 {
t[i], t[j] = t[j], t[i]
}
return string(t)
}
return r
}
Hosted at github: https://github.com/xor-gate/go-bjf
shareimprove this answer edited Jan 3 '16 at 20:18 answered Dec 6 '15 at 20:50
Jerry Jacobs
688
add a comment
up /**
* <p>
vote0do * Integer to character and vice-versa
wn vote * </p>
*
*/
public class TinyUrl {
return num;
}
}
class TinyUrlTest{
Hrishikesh Mishra
1,0261018
add a comment
up My python3 version
vote0do
base_list =
wn vote list("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
)
base = len(base_list)
if __name__ == '__main__':
encode(341413134141)
decode("60FoItT")
shareimprove this answer edited Sep 19 '16 at 7:10 answered Sep 19 '16 at 7:04
wyx
1821212
add a comment
up Here is Node.js implementation that is likely to bit.ly. generate highly random 7 character
vote0do string. using Node.js crypto to generate highly random 25 charset than random select 7
wn vote
character.
Hafiz Arslan
167213
add a comment
active
3 months ago
€35K - €90KREMOTERELOCATION
springhybris
ColdFusion Developer
REMOTE
coldfusion
C# (.NET) Software Architect - $60k
REMOTE
.nettdd
Lisp Software Architect - $60k
REMOTE
cc++
38 People Chatting
JavaScript
2 hours ago - RaisingAgent
PHP
2 hours ago - NikiC
Linked
10
How do URL shorteners guarantee unique URLs when they don't expire?
19
12
How do URL shortener calculate the URL key? How do they work?
Related
2989
1822
3413
2706
2063
2208
3106
about us tour help blog chat data legal privacy policy work here advertising info developer jobs
Stack Overflow Geographic Information Code Review Photography English Language & Usa
Server Fault Systems Magento Science Fiction & Fantasy Skeptics
Super User Electrical Engineering Signal Processing Graphic Design Mi Yodeya (Judaism)
Web Applications Android Enthusiasts Raspberry Pi Movies & TV Travel
Ask Ubuntu Information Security Programming Puzzles & Music: Practice & Theory Christianity
Webmasters Database Administrators Code Golf Seasoned Advice (cooking) English Language Learne
Game Development Drupal Answers more (7) Home Improvement Japanese Language
TeX - LaTeX SharePoint Personal Finance & Money Arqade (gaming)
Software Engineering User Experience Academia Bicycles
Unix & Linux Mathematica more (8) Role-playing Games
Ask Different (Apple) Salesforce Anime & Manga
WordPress Development ExpressionEngine® Answers Motor Vehicle
Cryptography Maintenance & Repair
more (17)
Early detection of
Twitter
trends explained
« Previous
Next »
A couple of weeks ago on Halloween night, I was out with some friends when
my advisor sent me a message to check web.mit.edu, right now. It took me a
few seconds of staring to realize that an article about my masters thesis work on
a nonparametric approach to detecting trends on Twitter was on the homepage
of MIT. Over the next few days, it was picked up
by Forbes, Wired, Mashable, Engadget, The Boston Herald and others, and my
inbox and Twitter Connect tab were abuzz like never before.
There was a lot of interest in how this thing works and in this post I want to give
an informal overview of the method Prof. Shah and I developed. But first, let me
start with a story…
A scandal
On June 27, 2012, Barclays Bank was fined $450 million for manipulating
the Libor interest rate, in what was possibly the biggest banking fraud scandal in
history. People were in uproar about this, and many took their outrage to
Twitter. In retrospect, “#Barclays” was bound to become a popular, or
“trending” topic. But how soon could one have known this with reasonable
certainty? Twitter’s algorithm detected “#Barclays” as a trend at 12:49pm GMT
following a big jump in activity around noon (Figure 1).
Figure 1
But is there something about the preceding activity that would have allowed us
to detect it earlier? It turns out that there is. We detected it at 12:03, more
than 45 minutes in advance. Overall, we were able to detect trends in
advance of Twitter 79% of the time, with a mean early advantage of
1.43 hours and an accuracy of 95%.
In this post I’ll tell you how we did it. But before diving into our approach, I want
to motivate the thinking behind it by going over another approach to detecting
trends.
Figure 2
Figure 3
A data-driven approach
Having outlined this data-driven approach, let’s dive into the actual algorithm.
Our algorithm
Suppose we are tracking the activity of a new topic. To decide whether a topic is
trending at some time we take some recent activity, which we call
the observation , and compare it to example patterns of activity from topics
that became trending in the past and topics that did not.
Each of these examples takes a vote on whether the topic is trending or
not trending (Figure 5). Positive, or trending examples ( in Figure 5) vote
“trending” and negative, or non-trending examples ( in Figure 5) vote “non-
trending”. The weight of each vote depends on the similarity, or distance
between the example and the observation according to a decaying exponential
Figure 5
Finally, we sum up all of the “trending” and “non-trending” votes, and see if the
ratio of these sums is greater than or less than 1.
This approach has some nice properties. The core computations are pretty
simple, as we only compute distances. It is scalable since computation of
distances can be parallelized. Lastly, it is nonparametric, which means we don’t
have to decide what model to use.
Results
To evaluate our approach, we collected 500 topics that trended in some time
window (sampled from previous lists of trending topics) and 500 that did not
(sampled from random phrases in tweets, with trending topics removed). We
then tried to predict, on a holdout set of 50% of the topics, which one would
trend and which one would not. For topics that both our algorithm and Twitter’s
detected as trending, we measured how early or late our algorithm was relative
to Twitter’s.
Our most striking result is that we were able to detect Twitter trends in advance
of Twitter’s trend detection algorithm a good percent of the time, while
maintaining a low rate of error. In 79% percent of cases, we detected trending
topics earlier than Twitter (1.43 hours earlier), and we managed to keep an error
rate of around 95% (4% false positive rate, 95% true positive rate).
Naturally, our algorithm has various parameters (most notably the scaling
parameter and the length of an observation signal) that affect the tradeoff
between the types of error and how early we can detect trends. If we are very
aggressive about detecting trends, we will have a high true positive rate and
early detection, but also a high false positive rate. If we are very conservative,
we will have a low false positive rate, but also a low true positive rate and late
detection. And there are various tradeoffs in between these extremes. Figure 6
shows a scatterplot of errors in the FPR(false positive rate)-TPR(true positive
rate) plane, where each point corresponds to a different combination of
parameters. The FPR-TPR plane is split up into three regions corresponding to
the aggressive (“top”), conservative (“bottom”), and in between (“center”)
strategies. Figure 6 also shows histograms of detection times for each of these
strategies.
Figure 6
Conclusion
And it has the potential to work for a lot more than just predicting trends on
Twitter. We can try this on traffic data to predict the duration of a bus ride, on
movie ticket sales, on stock prices, or any other time-varying measurements.
We are excited by the early results, but there’s a lot more work ahead. We are
continuing to investigate, both theoretically and experimentally, how well this
does with different kinds and amounts of data, and on tasks other than
classification. Stay tuned!
________________________________________________________
Notes:
Thanks to Ben Lerner, Caitlin Mehl, and Coleman Shelton for reading drafts of
this.
For a less technical look, Prof. Shah gave a great talk at the MIT Museum on
Friday, November 9th:
Advertisements
Share this:
Share
Related
Information Diffusion on TwitterIn "projects"
The Statistical Structure of RhythmIn "projects"
Do Something That Moves YouIn "thoughts"
Tags: data, machine learning, MIT, Nikolov, nonparametric, Shah, statistics, trends, twitter
69 comments
1. Pingback: Early detection of Twitter trends explained | My Daily Feeds
2.
b0b0b0b
November 16, 2012 at 11:35 pm
How did you get your tweet data? Without firehose access (maybe even with), is
it possible there is an inherent bias in twitter’s infrastructure that your algorithm
has learned?
o
snikolov
November 17, 2012 at 12:02 am
You can get the tweet data through the twitter API, which gives you a random
sample of the firehose (though I have no idea if it is truly uniform).
3.
Ivan Yurchenko
November 17, 2012 at 6:19 am
o
snikolov
November 17, 2012 at 3:13 pm
Thanks!
4.
Uzair
November 17, 2012 at 7:20 am
Isn’t this incredibly basic? It’s basically photometric similarity (except you
haven’t mentioned the importance of making the data scale-free here). I
thought this was fairly common for comparing time series?
o
snikolov
November 17, 2012 at 3:11 pm
Indeed, the method is surprisingly simple. As far as making the data scale-free, I
bet this would improve performance in practice (better accuracy given the
amount of data, or less data needed for a desired accuracy). In theory, though,
if we have enough data, the data itself should sufficiently cover all time scales,
without doing any extra normalization.
5.
acoulton
November 17, 2012 at 11:53 am
This is a really interesting approach. I could also see it being useful with
software/systems metrics (given access to a wide enough range of data).
For example, predicting when to scale up or down clusters based on what’s
about to happen (rather than waiting until the servers are already somewhat
overloaded). Or alerting an engineer when the system might be about to crash
(rather than waiting for the metrics that indicate it has already) so they can take
preventative access or at least be at their desk when it happens. Lots of
possibilities where currently we’re limited to rough guesses based on point in
time values and again where there’s a range of semi-predicatable patterns
leading up to an event.
o
snikolov
November 17, 2012 at 3:16 pm
Yes! I’d love to apply this to other domains that are serious pain-points for
people. Monitoring a complex software system or forecasting cluster usage
would be two excellent things to try.
Trending topics
A word, phrase or topic that is tagged at a greater rate than other
tags is said to be a trending topic. Trending topics become
popular either through a concerted effort by users or because of
an event that prompts people to talk about one specific topic.
These topics help Twitter and their users to understand what is
happening in the world.
1
@miguno The #Storm project rocks for real-time distributed #data processing!
1
2storm
data
In this example we can see that over time “scala” has become the
hottest trending topic.
Sliding Windows
The last background aspect I want to cover are sliding windows
aka rolling counts. A picture is worth a thousand words:
Figure 1: As the sliding window advances, the slice of its input
data changes. In the example above the algorithm uses the
current sliding window data to compute the sum of the window’s
elements.
A formula might also be worth a bunch of words – ok, ok, maybe
not a full thousand of them – so mathematically speaking we
could formalize such a sliding-window sum algorithm as follows:
m-sized rolling sum=∑i=ti+melement(i)m-sized rolling
sum=∑i=ti+melement(i)
where t continually advances (most often with time) and m is the
window size.
From size to time: If the window is advanced with time, say
every N minutes, then the individual elements in the input
represent data collected over the same interval of time
(here: N minutes). In that case the window size is equivalent to N
x m minutes. Simply speaking, if N=1 and m=5, then our sliding
window algorithm emits the latest five-minute aggregates every
one minute.
Now that we have introduced trending topics and sliding
windows we can finally start talking about writing code for Storm
that implements all this in practice – large-scale, distributed, in
real time.
Before We Start
About storm-starter
The storm-starter project on GitHub provides example
implementations of various real-time data processing topologies
such as a simple streaming WordCount algorithm. It also includes
a Rolling Top Words topology that can be used for computing
trending topics, the purpose of which is exactly what I want to
cover in this article.
When I began to tackle trending topic analysis with Storm I
expected that I could re-use most if not all of the Rolling Top
Words code in storm-starter . But I soon realized that the old code
would need some serious redesigning and refactoring before one
could actually use it in a real-world environment – including being
able to efficiently maintain and augment the code in a team of
engineers across release cycles.
In the next section I will briefly summarize the state of the Rolling
Top Words topology before and after my refactoring to highlight
some important changes and things to consider when writing your
own Storm code. Then I will continue with covering the most
important aspects of the new implementation in further detail.
And of course I contributed the new implementation back to the
Storm project.
Dat - SlotBasedCounter,SlidingWindowC
a ounter, Rankings,Rankable,Rankabl
Stru eObjectWithFields
ctur
es
1. The new code should be clean and easy to understand, both for
the benefit of other developers when adapting or maintaining
the code and for reasoning about its correctness. Notably, the
code should decouple its data structures from the Storm sub-
system and, if possible, favor native Storm features for
concurrency instead of custom approaches.
2. The new code should be covered by meaningful unit tests.
3. The new code should be good enough to contribute it back to
the Storm project to help its community.
1// such code from the old RollingCountObjects bolt is not needed anymore
2long delta = millisPerBucket(_numBuckets)
3 - (System.currentTimeMillis() % millisPerBucket(_numBuckets));
4Utils.sleep(delta);
SlotBasedCounter
The SlotBasedCounter class provides per-slot counts of the
occurrences of objects. The number of slots of a given counter
instance is fixed. The class provides four public methods:
SlotBasedCounter API
Using SlotBasedCounter
SlidingWindowCounter
The SlidingWindowCounter class provides rolling counts of the
occurrences of “things”, i.e. a sliding window count for each
tracked object. Its counting functionality is based on the
previously described SlotBasedCounter . The size of the sliding
window is equivalent to the (fixed) number of slots number of a
given SlidingWindowCounter instance. It is used by RollingCountBolt for
counting incoming data tuples.
The class provides two public methods:
SlidingWindowCounter API
If you have not heard about LMAX Disruptor before, make sure to
read their LMAX technical paper (PDF) on the LMAX homepage for
inspirations. It’s worth the time!
Figure 3: The SlidingWindowCounter class keeps track of
multiple rolling counts of objects, i.e. a sliding window count for
each tracked object. Please note that the example of an 8-slot
sliding window counter above is simplified as it only shows a
single count per slot. In reality SlidingWindowCounter tracks multiple
counts for multiple objects.
Here is an illustration showing the behavior
of SlidingWindowCounter over multiple iterations:
Figure 4: Example of SlidingWindowCounter behavior for a counter of
size 4. Again, the example is simplified as it only shows a single
count per slot.
Rankings API
Whenever you update Rankings with new data, it will discard any
elements that are smaller than the updated top N , where N is the
maximum size of the Rankings instance (e.g. 10 for a top 10
ranking).
Now the sorting aspect of the ranking is driven by the natural
order of the ranked objects. In my specific case, I created
a Rankable interface that in turn implements
the Comparable interface. In practice, you simply pass
a Rankable object to the Rankings class, and the latter will update its
rankings accordingly.
Using the Rankings class
1@Override
2void updateRankingsWithTuple(Tuple tuple) {
3 Rankable rankable = RankableObjectWithFields.from(tuple);
4 super.getRankings().updateWith(rankable);
5}
Have a look
at Rankings, Rankable and RankableObjectWithFields for details.
If you run into a situation where you have to implement classes
like these yourself, make sure you follow good engineering
practice and add standard methods such
as equals() and hashCode() as well to your data structures.
TestWordSpout
The only spout we will be using is the TestWordSpout that is part
of backtype.storm.testing package of Storm itself. I will not cover the
spout in detail because it is a trivial class. The only thing it does is
to select a random word from a fixed list of five words (“nathan”,
“mike”, “jackson”, “golda”, “bertels”) and emit that word to the
downstream topology every 100ms. For the sake of this article,
we consider these words to be our “topics”, of which we want to
identify the trending ones.
Note: Because TestWordSpout selects its output words at random
(and each word having the same probability of being selected) in
most cases the counts of the various words are pretty close to
each other. This is ok for example code such as ours. In a
production setting though you most likely want to generate
“better” simulation data.
The spout’s output can be visualized as follows. Note that
the @XXXms milliseconds timeline is not part of the actual output.
1
2@100ms: nathan
3@200ms: golda
4@300ms: golda
5@400ms: jackson
6@500ms: mike
7@600ms: nathan
8@700ms: bertels
...
1@Override
2public Map<String, Object> getComponentConfiguration() {
3 Config conf = new Config();
4 int tickFrequencyInSeconds = 10;
5 conf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, tickFrequencyInSeconds);
6 return conf;
7}
1@Override
2public void execute(Tuple tuple) {
3 if (isTickTuple(tuple)) {
4 // now you can trigger e.g. a periodic activity
5 }
6 else {
7 // do something with the normal tuple
8 }
9}
1
0private static boolean isTickTuple(Tuple tuple) {
1 return tuple.getSourceComponent().equals(Constants.SYSTEM_COMPONENT_ID)
1 && tuple.getSourceStreamId().equals(Constants.SYSTEM_TICK_STREAM_ID);
1}
2
1
3
1
4
RollingCountBolt
This bolt performs rolling counts of incoming objects, i.e. sliding
window based counting. Accordingly it uses
the SlidingWindowCounter class described above to achieve this. In
contrast to the old implementation only this bolt (more correctly:
the instances of this bolt that run as Storm tasks) is interacting
with the SlidingWindowCounter data structure. Each instance of the
bolt has its own private SlidingWindowCounter field, which eliminates
the need for any custom inter-thread communication and
synchronization.
The bolt combines the previously described tick tuples (that
trigger at fix intervals in time) with the time-agnostic behavior
of SlidingWindowCounter to achieve time-based sliding window
counting. Whenever the bolt receives a tick tuple, it will advance
the window of its private SlidingWindowCounter instance and emit its
latest rolling counts. In the case of normal tuples it will simply
count the object and ack the tuple.
RollingCountBolt
1@Override
2public void execute(Tuple tuple) {
3 if (TupleHelpers.isTickTuple(tuple)) {
4 LOG.info("Received tick tuple, triggering emit of current window counts");
5 emitCurrentWindowCounts();
6 }
7 else {
8 countObjAndAck(tuple);
9 }
1}
0
1private void emitCurrentWindowCounts() {
1 Map<Object, Long> counts = counter.getCountsThenAdvanceWindow();
1 ...
2 emit(counts, actualWindowLengthInSeconds);
1}
3
1private void emit(Map<Object, Long> counts) {
4 for (Entry<Object, Long> entry : counts.entrySet()) {
1 Object obj = entry.getKey();
5 Long count = entry.getValue();
1 collector.emit(new Values(obj, count));
6 }
1}
7
1private void countObjAndAck(Tuple tuple) {
8 Object obj = tuple.getValue(0);
1 counter.incrementCount(obj);
9 collector.ack(tuple);
2}
0
2
1
2
2
2
3
2
4
2
5
2
6
2
7
2
8
2
9
3
0
That’s all there is to it! The new tick tuples in Storm 0.8 and the
cleaned code of the bolt and its collaborators also make the code
much more testable (the new code of this bolt has 98% test
coverage). Compare the code above to the old implementation of
the bolt and decide for yourself which one you’d prefer adapting
or maintaining:
1
2
3
4
@Test
5
public void shouldEmitNothingIfNoObjectHasBeenCountedYetAndTickTupleIsReceived() {
6
// given
7
Tuple tickTuple = MockTupleHelpers.mockTickTuple();
8
RollingCountBolt bolt = new RollingCountBolt();
9
Map conf = mock(Map.class);
1
TopologyContext context = mock(TopologyContext.class);
0
OutputCollector collector = mock(OutputCollector.class);
1
bolt.prepare(conf, context, collector);
1
1
// when
2
bolt.execute(tickTuple);
1
3
// then
1
verifyZeroInteractions(collector);
4
}
1
5
1
6
AbstractRankerBolt
This abstract bolt provides the basic behavior of bolts that rank
objects according to their natural order. It uses the template
method design pattern for its execute() method to allow actual bolt
implementations to specify how incoming tuples are processed,
i.e. how the objects embedded within those tuples are retrieved
and counted.
This bolt has a private Rankings field to rank incoming tuples (those
must contain Rankable objects, of course) according to their natural
order.
AbstractRankerBolt
1
2
3// This method functions as a template method (design pattern).
4@Override
5public final void execute(Tuple tuple, BasicOutputCollector collector) {
6 if (TupleHelpers.isTickTuple(tuple)) {
7 getLogger().info("Received tick tuple, triggering emit of current rankings");
8 emitRankings(collector);
9 }
1 else {
0 updateRankingsWithTuple(tuple);
1 }
1}
1
2abstract void updateRankingsWithTuple(Tuple tuple);
1
3
IntermediateRankingsBolt
This bolt extends AbstractRankerBolt and ranks incoming objects by
their count in order to produce intermediate rankings. This type of
aggregation is similar to the functionality of a combiner in
Hadoop. The topology runs many of such intermediate ranking
bolts in parallel to distribute the load of processing the incoming
rolling counts from the RollingCountBolt instances.
This bolt only needs to
override updateRankingsWithTuple() of AbstractRankerBolt :
IntermediateRankingsBolt
1@Override
2void updateRankingsWithTuple(Tuple tuple) {
3 Rankable rankable = RankableObjectWithFields.from(tuple);
4 super.getRankings().updateWith(rankable);
5}
TotalRankingsBolt
This bolt extends AbstractRankerBolt and merges incoming
intermediate Rankings emitted by
the IntermediateRankingsBolt instances.
Like IntermediateRankingsBolt , this bolt only needs to override
the updateRankingsWithTuple() method:
TotalRankingsBolt
1@Override
2void updateRankingsWithTuple(Tuple tuple) {
3 Rankings rankingsToBeMerged = (Rankings) tuple.getValue(0);
4 super.getRankings().updateWith(rankingsToBeMerged);
5}
1@Override
2public Map<String, Object> getComponentConfiguration() {
3 Map<String, Object> conf = new HashMap<String, Object>();
4 conf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, emitFrequencyInSeconds);
5 // run only a single instance of this bolt in the Storm topology
6 conf.setMaxTaskParallelism(1);
7 return conf;
8}
RollingTopWords
The class RollingTopWords ties all the previously discussed code
pieces together. It implements the actual Storm topology,
configures spouts and bolts, wires them together and launches
the topology in local mode (Storm’s local mode is similar to
a pseudo-distributed, single-node Hadoop cluster).
By default, it will produce the top 5 rolling words (our trending
topics) and run for one minute before terminating. If you want to
twiddle with the topology’s configuration settings, here are the
most important:
Then you must build and install the (latest) Storm jars locally, see
the storm-starter README:
1# Must be run from the top-level directory of the Storm code repository
2$ mvn clean install -DskipTests=true
1$ cd examples/storm-starter
2$ mvn compile exec:java -Dstorm.topology=storm.starter.RollingTopWords
By default the topology will run for one minute and then
terminate automatically.
Thread- TestWordSpout
37
Thread- TestWordSpout
39
Thread- RollingCountBolt
19
Thread- RollingCountBolt
21
Thread- RollingCountBolt
25
Thread- IntermediateRanking
31 sBolt
Thread- IntermediateRanking
33 sBolt
Thread- TotalRankingsBolt
27
Note: The Rolling Top Words code in the storm-starter repository runs
more instances of the various spouts and bolts than the code
used in this article. I downscaled the settings only to make the
figures etc. easier to read. This means your own logging output
will look slightly different.
The topology has just started to run. The spouts generate their
first output messages:
Also, there are some minor changes in my own code that I did not
contribute back to storm-starter because I did not want to introduce
too many changes at once (such as a
refactored TestWordSpout class).
Summary
In this article I described how to implement a distributed, real-
time trending topics algorithm in Storm. It uses the latest features
available in Storm 0.8 (namely tick tuples) and should be a good
starting point for anyone trying to implement such an algorithm
for their own application. The new code is now available in the
official storm-starter repository, so feel free to take a closer look.
You might ask whether there is a use of a distributed sliding
window analysis beyond the use case I presented in this article.
And for sure there is. The sliding window analysis described here
applies to a broader range of problems than computing trending
topics. Another typical area of application is real-time
infrastructure monitoring, for instance to identify broken servers
by detecting a surge of errors originating from problematic
machines. A similar use case is identifying attacks against your
technical infrastructure, notably flood-type DDoS attacks. All of
these scenarios can benefit from sliding window analyses of
incoming real-time data through tools such as Storm.
If you think the starter code can be improved further, please
contribute your changes back to thestorm-starter component in
the official Storm project.
Related Links
Understanding the Parallelism of a Storm Topology
Interested in more? You can subscribe to this blog, or follow me
on Twitter.
Posted by Michael G. Noll Jan 18th, 2013 Filed
under Java, Programming, Real-time, Storm
« Understanding the Parallelism of a Storm Topology Bootstrapping a Java
project with Gradle, TestNG, Mockito and Cobertura for Eclipse and Jenkins »
Comments
Architecture:
A bare minimum crawler needs at least these components:
1. DNS resolving: This minor operation, when crawling on a large scale adds up
to a big bottleneck. If not tackled, your system might spend more time on
waiting to resolve domain names than on fetching and parsing. It is advisable
to maintain local caches to avoid repeated requests.
2. Politeness: Every site has different politeness requirements and ignoring
might lead to IP blocks. Expect mails from web admins! [5] . You need to
cache the robot.txt files for every domain and follow the rules to avoid getting
blocked. Also sites usually have time-gap requirements and this means
slowing the fetching rate. If you system is distributed, better to aggregate all
requests pertaining to a domain on the same node.
3. Adversaries: Don't expect the web world to be nice to your bot!. There are
many crawler traps, spam sites and cloaked content. Crawler traps have large
automated URLS with potential loops which leads to the crawler getting
struck there. You need to smartly classify valid domains from spam domains.
Domain reputation from user input could be one such. There are other
redundant web content (some unintentional) too.
4. Seed and Content selection: You need to come up with a good set of seed
domains and it is desirable to have some mechanism to rank domains/URL
based on content for effective prioritisation.
More problems (Research oriented):
Implementation specifics:
This thesis work Building blocks of a scalable web crawler[7] details crawling from
implementation point of view.
Programming Language: Any high level language with good network library that you
are comfortable with is fine. I personally prefer Python/Java. As your crawler project
might grow in terms of code size it will be hard to manage if you develop in a design-
restricted programming language. While it is possible to build a crawler using just unix
commands and shell script, you might not want to do so for obvious reasons.
[1] Olston, C., & Najork, M. (2010). Web crawling. Foundations and Trends in
Information Retrieval, 4(3), 175-246.
[2] Pant, G., Srinivasan, P., & Menczer, F. (2004). Crawling the web. In Web Dynamics
(pp. 153-177). Springer Berlin Heidelberg.
[3] Heydon, A., & Najork, M. (1999). Mercator: A scalable, extensible web
crawler.World Wide Web, 2(4), 219-229.
[4] Boldi, P., Codenotti, B., Santini, M., & Vigna, S. (2004). Ubicrawler: A scalable fully
distributed web crawler. Software: Practice and Experience, 34(8), 711-726.
[5] Lee, H. T., Leonard, D., Wang, X., & Loguinov, D. (2009). IRLbot: scaling to 6
billion pages and beyond. ACM Transactions on the Web (TWEB), 3(3), 8.
[6] Harth, A., Umbrich, J., & Decker, S. (2006). Multicrawler: A pipelined architecture
for crawling and indexing semantic web data. In The Semantic Web-ISWC 2006 (pp.
258-271). Springer Berlin Heidelberg.
[7] Seeger, M. (2010). Building blocks of a scalable web crawler. Master's thesis,
Stuttgart Media University.
Language and framework do matter a lot. The rule of thumb is not reinventing the
wheel. If there are existing tools that can ease your work, just grab it. If I were to build
a web crawler from scratch, I would choose Python. Some advantages include:
Language is simple to write. The syntax is concise and it's one of the best
languages that allow you to build things fast.
There are tons of libraries/frameworks that help you build a web crawler. For
instance, Scrapy is a very fast and powerful framework for crawling.
Just Google “python web crawler”, you're gonna get hundreds or thousands of
results. You don't need to build everything “from scratch” since so many
existing tools/codes can save you tons of time.
It's also worth to note that one disadvantage of Python is the performance. Compared
to other languages like C++, Python is relatively slower.
In addition, you'd better have a clear understanding of how web crawler works in
essence and what kind of problems you need to consider. I'd recommend you read the
article - Build a Web Crawler that has a very in-depth analysis/introduction of this
topic.
In a nutshell, to crawler a single web page, all we need is to issue a HTTP GET request
to the corresponding URL and parse the response data, which is the core of a crawler.
Start with a URL pool, we can keep adding URLs from sites we crawled and the
process continues. Couple of things you should figure out:
Crawling frequency - For some small websites, it’s very likely that their
servers cannot handle very frequent request. One approach is to follow the
robot.txt of each site.
Dedup - In a single machine, you can keep the URL pool in memory and
remove duplicate entries. However, things become more complicated in a
distributed system. Basically multiple crawlers may extract the same URL
from different web pages and they all want to add this URL to the URL pool.
Parsing - The challenge is that you will always find strange markups, URLs
etc. in the HTML code and it’s hard to cover all corner cases.
19.8k Views · View Upvotes
My recommendations are:
C - If you need your crawler should be extremely fast and less memory
consumption.wget is written in C.
Python/Perl - Easy to develop has a lot of libraries. But i don't have a lot
of experience on these languages.
Wikipedia has a great article about the web-crawler please have a look.
http://en.wikipedia.org/wiki/Web...
Jake Kovoor
Written Mar 24
I was actually trying to find a way to do this a few days ago,
and I came up on a great, quick, and simple way to create a web crawler using Python
code.
ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ
ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ
I have tried the following code a few days ago on my Python 3.6.1 (which is the latest
as of 21st March 2017) and it should work for you too.
All you have to do is just copy+paste the code into your Python IDE, and it should work
for you.
ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ
If you are having any problems, or if you found any errors, just drop me a message and
let's work it out together. :-)
732 Views · View Upvotes
To learn the theory behind how a web crawler is built and functions you can refer to an
excellent and ubiquitously used textbook 'Introduction to Information Retrieval' by
Stanford professors. Specifically chapter 20 titled 'Web Crawling and Indices' talks
about the architecture and functioning of a web crawler.
http://www.udacity.com/overview/...
BTW the original Google search engine was built with Python -- the crawler was
written by Scott Hassan.
Your web crawler is really just a function. It's input is a set of seed URLs (or entry
points), and it's output is a set of HTML pages (or results).
Inside this web crawler function is something called the "horizon" which is just a list
containing all unvisited URLs that your crawler intends to visit.
I think that is a sufficient backbone to build off of. Certainly any production crawler
will have much more that needs to be engineered.
Missing features of the above crawler include, but are not limited to:
1. Robots.txt handling
2. Crawl depth limiting
3. Request rate limiting
4. Incremental crawling
5. Non HTML media type support
6. Page deduplication (URL canonicalization)
7. And many more!
28.6k Views · View Upvotes
1. HTTP Fetcher: to extract the webpages from the target site servers
4. URL Queue Manager: this creates a queue of URLs according to the priority
5. Database: to store extracted data for further analysis and application in the business
While crawling large scale websites, you need to factor in the following:
1. I/O mechanism
2. Multi-threading architecture
4. DNS resolving
5. Robots.txt management
8. De-duplication
Apart from that you need to ensure that the choice of programming language is correct
so that you can extract maximum utility from the web scraper. Many prefer Python and
Perl to do most of the heavy lifting in the scraping exercise.
Here are the key steps that would be taken by the crawler:
2. For each of the URL in the list, the crawler will issue a ‘HTTP Get Request’ and
retrieve the web page content
3. Parse the HTML content of the page and retrieve the probable URLs the crawler
needs to crawl
4. Update the list of websites with new URLs and continue crawling with the program
A successful crawler must consider the server load it will place on the URL it requests.
The crawling frequency of your program needs to be set to one or two times a day
(reasonable frequency that will not cause server crash).
1.5k Views · View Upvotes
Peter Jaap, ecommerce | webdeveloper | entrepreneur | Magento evangelist |
Drupalist
Written Aug 7, 2012
I've always built my spiders (in PHP) with either Simple HTML DOM Parser
(http://simplehtmldom.sourceforge...) or Snoopy (http://sourceforge.net/projects/...).
While the first is easier to use when traversing large DOM structures (especially if you
are used to the jQuery CSS selectors syntax), Snoopy is a bit more abstract in use.
Jesus Vassa
Written Jul 1, 2015
Building a web crawler from scratch is not an easy task at all. It will require immense
time and dedication. Also, you might get stuck up half-way through due to its
complexity. So, I would suggest you to hire experts who will be able to guide you while
you build your web crawler.
You could consider getting in touch with the expert team from this website. They are
the world’s most sophisticated ecommerce platform that provides A-Z of ecommerce
solutions.
Their Easy Data Feed tool is a data extraction software, which is designed to quickly
and easily download inventory, pricing, and product information. These data can be
downloaded into a usable spreadsheet from your drop ship supplier’s online portal
without relying on the drop shipper. Also, they can extract inventory data from any
website, password protected website, API, email or FTP and plug it right into your
store.
Now we have a polite web crawler made in python and we call it TWMBot. You can see
more details on our website: http://thewebminer.com
Related Questions
I want to build a web search engine using Python. Where can I find more details on building an efficient
crawler? I'm also looking for approac...
Kindly recommend a BOOK for building the web crawler from scratch?
Why did Google move from Python to C++ for use in its crawler?